生命体个数
原题链接:4885.聊天2023-08-17 15:52:12
发布于:河北
题解:
#include<bits/stdc++.h>
using namespace std;
int n, m;
char g[5010][5010];
bool vis[5010][5010];
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
struct node{
int x, y;
};
void bfs(int sx, int sy)
{
queue<node> q;
node p;
q.push({sx, sy});
vis[sx][sy] = 1;
while(!q.empty())
{
p = q.front();
q.pop();
for(int i = 0; i <= 3; i++)
{
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if(nx < 1 || ny < 1) continue;
if(nx > n || ny > m) continue;
if(vis[nx][ny]) continue;
if(g[nx][ny] == '0') continue;
q.push({nx, ny});
vis[nx][ny] = 1;
}
}
}
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> g[i][j];
}
}
int ans = 0;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
if(!vis[i][j] && g[i][j] != '0')
{
ans++;
bfs(i, j);
}
}
}
cout << ans << endl;
return 0;
}
这里空空如也
有帮助,赞一个