细胞 题解dfs+bfs
2026-11-20 20:07:25
发布于:浙江
1阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
long long n,m,ans=0;
char a[1010][1010];
long long vis[1010][1010];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
void bfs(int x,int y){
vis[x][y]=1;
for(int i=0;i<4;i++){
int x2=x+dx[i];
int y2=y+dy[i];
if(x2>=1&&x2<=n&&y2>=1&&y2<=m&&a[x2][y2]!='0'&&!vis[x2][y2]){
bfs(x2,y2);
}
}
}
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]!='0'&&!vis[i][j]){
ans++;
bfs(i,j);
}
}
}
cout<<ans;
return 0;
}
/*一矩形阵列由数字0到9组成,数字1到9代表细胞,细胞的定义为沿细胞数字上下左右还是细胞数字则为同一细胞,
求给定矩形阵列的细胞个数。如:阵列
4 10
0234500067
1034560500
2045600671
0000000089
有4个细胞。
*/
#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
char a[N][N];
int n, m;
// 方向:下、右、上、左,和原来dfs顺序一致
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
struct Point {
int x, y;
};
// BFS:返回当前这个细胞块的格子数量
void bfs(int sx, int sy)
{
queue<Point> q;
//Point tmp;
//tmp.x=sx;tmp.y=sy;
//q.push(tmp);
q.push({sx, sy});
a[sx][sy] = '0';
//int cnt = 1;
while (!q.empty())
{
//Point tmp1;
Point now = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = now.x + dx[i];
int ny = now.y + dy[i];
// 边界判断 + 是细胞'1'
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && a[nx][ny]!='0')
{
a[nx][ny] = '0';
/*Point df;
df.x=nx;
df.y=ny;
q.push(df);
*/
q.push({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 block_num = 0; // 细胞块总数
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (a[i][j] != '0')
{
block_num++;
bfs(i, j);
}
}
}
cout << block_num << endl;
return 0;
}
这里空空如也







有帮助,赞一个