什么是联通块
对于蓝色的小块而言,四联通块(题目不说一般都是四联通)就是周围红色的区域,是可到达的位置,八联通块是加上黄色的位置
用dfs实现联通块模版
#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
int n, m, a[maxn][maxn];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
bool vis[maxn][maxn];
void dfs(int x, int y) {
if (x < 1 || y < 1 || x > n || y > n)
return ;
if (vis[x][y])
return ;
vis[x][y] = 1;
for (int i = 0; i < 4; i ++) {
int nx = x + dx[i], ny = y + dy[i];
dfs(nx, ny);
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
cin >> a[i][j];
int cnt = 0;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
if (!vis[i][j])
cnt ++, dfs(i, j);
cout << cnt;
return 0;
}
用bfs实现联通块模版
#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
int n, m, a[maxn][maxn];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
bool vis[maxn][maxn];
struct node {
int x, y;
};
void bfs(int x, int y) {
queue<node> q;
q.push((node) {
x, y
}) ;
while (!q.empty()) {
node t = q.front();
q.pop();
if (t.x < 1 || t.x > n || t.y > m || t.y < 1)
continue;
if (vis[t.x][t.y])
continue;
vis[t.x][t.y] = 1;
for (int i = 0; i <= 4; i ++) {
int nx = t.x + dx[i], ny = t.y + dy[i];
q.push((node) {
nx, ny
});
}
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
cin >> a[i][j];
int cnt = 0;
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
if (!vis[i][j])
cnt ++, bfs(i, j);
cout << cnt;
return 0;
}