#寻找连通块
题目的大致意思就是给你一张地图,找到规定的字符所组成的连通块的数量。
Sample Input
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0
Sample Output
0
1
2
2
这个题,我们找由@组成的连通块的数量。这里的连通块的定义为以某点为中心,向周围八个点扩散的都是和中心点连通的点。
这仍然是个dfs的题,当然,也有bfs的解法。
#include<iostream>
#include<queue>
#include<string.h>
#include<string>
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e3+5;
int n,m,ans=0;
char mp[N][N];
int flag[N][N];//标记数组
int c[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};//方向数组
void dfs(int x,int y)
{
for(int i=0;i<8;i++)
{
int dx=x+c[i][0];
int dy=y+c[i][1];
if(mp[dx][dy]=='@'&&dx>=1&&dy>=1&&dx<=n&&dy<=m&&!flag[dx][dy])
{
flag[dx][dy]=1;//把连通的点都标记,下次就不会再走这里
dfs(dx,dy);
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin>>n>>m)
{
if(n==0&&m==0)
break;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>mp[i][j];
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(!flag[i][j]&&mp[i][j]=='@')
{
flag[i][j]=1;//标记这个点
ans++;//连通块的数量加一
dfs(i,j);//以这点为中心,向周围扩散,寻找连通块
}
}
}
cout<<ans<<endl;
memset(flag,0,sizeof flag);
ans=0;
}
}