Files
python/TangDou/XiTi/1381_dfs.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

45 lines
1017 B
C++
Raw Permalink 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.

#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int g[N][N];
int n, m;
int dx[] = {-1, 0, 1, 0}; //上右下左
int dy[] = {0, 1, 0, -1}; //上右下左
//总个数
int ans;
//深度优先搜索
void dfs(int x, int y) {
g[x][y] = 0; //标识为0
for (int i = 0; i < 4; i++) {
int tx = x + dx[i], ty = y + dy[i];
if (tx < 1 || tx > n || ty < 1 || ty > m) continue;
if (g[tx][ty]) dfs(tx, ty);
}
}
int main() {
cin >> n >> m;
//黑色在方格图中被标为1白色格子标为0
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> g[i][j];
//深度优先搜索
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
//发现有黑色的方块
if (g[i][j]) {
//黑色方块数+1
ans++;
//深搜
dfs(i, j);
}
cout << ans << endl;
return 0;
}