样例输入
2
5 5
01111
11001
10101
10001
11111
5 6
111111
100001
010101
100001
111111
样例输出
1
3
解题思路
从(0,0)(0,0)(0,0)开始染色,把遇到的0全部染成2,这样没染色的部分,一定为环,接着再搜索环的个数即可。
注意:开始染色的时候,可能有斜角,得使用八向搜索;搜索环的时候则用四向搜索。
参考代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 5e1 + 5;
int T, m, n;
char g[N][N];
int dx[8] = {0, 0, 1, -1, 1, 1, -1, -1};
int dy[8] = {1, -1, 0, 0, -1, 1, 1, -1};
int ans;
struct point {
int x, y;
};
void bfs1() {
queue<point>q;
g[0][0] = '2';
q.push({0, 0});
while (!q.empty()) {
point now = q.front();
q.pop();
for (int i = 0; i < 8; i++) {
int tx = now.x + dx[i];
int ty = now.y + dy[i];
if (tx >= 0 && ty >= 0 && tx <= m + 1 && ty <= n + 1) {
if (g[tx][ty] == '0') {
g[tx][ty] = '2';
q.push({tx, ty});
}
}
}
}
}
void bfs2(int x, int y) {
queue<point>q;
g[x][y] = '2';
q.push({x, y});
while (!q.empty()) {
point now = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int tx = now.x + dx[i];
int ty = now.y + dy[i];
if (tx >= 1 && ty >= 1 && tx <= m && ty <= n) {
if (g[tx][ty] == '0' || g[tx][ty] == '1') {
g[tx][ty] = '2';
q.push({tx, ty});
}
}
}
}
}
int main() {
cin >> T;
while (T--) {
cin >> m >> n;
memset(g, '0', sizeof(g));
ans = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
cin >> g[i][j];
}
}
bfs1();
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (g[i][j] == '1') {
ans++;
bfs2(i, j);
}
}
}
cout << ans << endl;
}
return 0;
}