难度:3
求数组连通块个数,dfs最基本的应用。
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
int m, n;
int r[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
int c[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
bool visit[105][105];
string s[105];
bool judge(int x, int y) {
if (x < 0 || y < 0 || x >= m || y >= n) return false;
return true;
}
void dfs(int x, int y) {
visit[x][y] = true;
for (int i = 0; i < 8; i++) {
int xx = x + r[i];
int yy = y + c[i];
if (judge(xx, yy) && s[xx][yy] == '@' && visit[xx][yy] == false) dfs(xx, yy);
}
}
int main() {
while (cin >> m >> n && m && n) {
for (int i = 0; i < m; i++) {
cin >> s[i];
}
int ans = 0;
fill(visit[0], visit[0] + 105 * 105, false);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (s[i][j] == '@' && visit[i][j] == false) {
dfs(i, j);
ans++;
}
}
}
cout << ans << endl;
}
return 0;
}