[uva] 11953 – battleships

出處

https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=3104

題意

問還剩下幾艘船

思路

遇到x就DFS

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include <string>
#include <vector>
#ifdef LOCAL
#include "stloutput.h"
#endif
#define INF 1000000000

using namespace std;
void (int x, int y, vector<string> &g) {
if (g[x][y] == '.') return;
g[x][y] = '.';
dfs(x + 1, y, g);
dfs(x, y + 1, g);
dfs(x, y - 1, g);
dfs(x - 1, y, g);
}

int main() {
int T;
cin >> T;
for (int t = 1; t <= T; t++) {
int N;
cin >> N;
vector<string> g;
string s;
g.push_back(string(N + 2, '.'));
for (int i = 0; i < N; i++) {
cin >> s;
g.push_back('.' + s + '.');
}
g.push_back(string(N + 2, '.'));
int cnt = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
if (g[i][j] == 'x') {
cnt++;
dfs(i, j, g);
}
}
}
cout << "Case " << t << ": " << cnt << endl;
}
}