Files
python/TangDou/LanQiaoBei/LanQiaoBei13ShengSai_ZJ_II/8.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

63 lines
1.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
有一片海域划分为N*M个方格,其中有些海域已被污染(用0表示),
有些海域没被污染(用1表示)。请问这片N*M海域中有几块是没被污染的独立海域
(没被污染的独立海域是指该块海域上下左右被已污染的海域包围,
且N*M以外的海域都为已被污染的海域)
例如:N=4,M=5,4*5的海域中,已被污染海域和没被污染的海域如下图:
这块4*5的海域,有3块海域(绿色)没被污染,因为每一块的上下左右都被污染的海域包围。
4 5
1 1 0 0 0
1 0 1 0 0
1 0 0 0 0
1 1 0 1 1
样例输出
3
*/
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 110;
int a[N][N];
int n, m;
int dx[] = {-1, 0, 1, 0}; //上右下左
int dy[] = {0, 1, 0, -1}; //上右下左
void bfs(int x, int y) {
a[x][y] = 0;
queue<PII> q;
q.push({x, y});
while (q.size()) {
auto u = q.front();
q.pop();
for (int i = 0; i <= 3; i++) {
int tx = u.x + dx[i], ty = u.y + dy[i];
if (tx < 1 || tx > n || ty < 1 || ty > m) continue;
if (a[tx][ty]) {
a[tx][ty] = 0;
q.push({tx, ty});
}
}
}
}
int res;
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> a[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (a[i][j]) {
bfs(i, j);
res++;
}
}
printf("%d", res);
return 0;
}