裸bfs。多加一些位置转移即可。
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
char s[105];
int map[105][105],n,m,cnt=0,bx,by;
int dx[]={0,1,0,-1,0,-1,1,1,-1,2,0,-2,0},dy[]={0,0,1,0,-1,-1,-1,1,1,0,2,0,-2};
bool vis[105][105];
struct code
{
int x,y;
};
queue <code> q;
bool judge(int x,int y)
{
if ((x>=1) && (x<=n) && (y>=1) && (y<=m) && (vis[x][y]==false) && (map[x][y]==1))
return true;
return false;
}
void bfs(int bx,int by)
{
code begin;
begin.x=bx;begin.y=by;
while (!q.empty())
q.pop();
vis[bx][by]=true;
q.push(begin);
while (!q.empty())
{
code head=q.front();
q.pop();
for (int i=1;i<=12;i++)
{
int tx=head.x+dx[i],ty=head.y+dy[i];
if (judge(tx,ty)==true)
{
code now;
now.x=tx;now.y=ty;
vis[tx][ty]=true;
q.push(now);
}
}
}
}
int main()
{
memset(vis,false,sizeof(vis));
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
{
scanf("%s",s);
for (int j=0;j<m;j++)
{
if (s[j]=='#') map[i][j+1]=1;
else map[i][j+1]=0;
}
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
if ((map[i][j]==1) && (vis[i][j]==false))
{
cnt++;
bfs(i,j);
}
}
printf("%d\n",cnt);
return 0;
}