细胞

方法1广搜:

送(1,1)开始逐个点bfs,先判断是否越界,然后若符合条件则标记为1,计数器++;

全部搜一遍后,输出计数器;

代码:

#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, m;
char mp[N][N];
bool vis[N][N];
void bfs(int x, int y)
{
queue<PII> q;
q.push({x,y});
vis[x][y] = 1;
while (!q.empty())
{
PII now =q.front();
q.pop();
int x=now.first, y=now.second;
int dx[4] ={0, 0, 1, -1}, dy[4] ={1, -1, 0, 0};
for (int i=0;i<4;i++ )
{
int xx=x + dx[i], yy=y+dy[i];
if (!vis[xx][yy] && xx >= 1 && yy >= 1 && xx <= n && y <= m && mp[xx][yy] != '0')
q.push({xx,yy}), vis[xx][yy] = 1;
}
}
}
int main()
{
cin>>n>>m;
for (int i=1; i<=n; i++ )
scanf("%s",mp[i]+ 1);
int ans=0;
for (int i=1; i<=n; i++ )
for (int j=1; j<=m; j++ )
if (!vis[i][j]&&mp[i][j]!= '0')
{
bfs(i,j);
ans ++ ;
}
cout<<ans;
return 0;
}

方法2深搜:

。。。

 

posted @ 2022-09-12 14:30  nnd昵称被使用?  阅读(22)  评论(0编辑  收藏  举报