注意的是,要将一个状态标记为已遍历之后再进队,而不能在每次出队的时候才将其标记为已遍历。
#include <stdio.h>
#include <queue>using namespace std;
typedef struct Node
{
int x, y;
}Node;queue<Node> Q;
int go[][2] = {1,0, -1,0, 0,1, 0,-1};
char map[20][20];int BFS(int h, int w)
{
Node now;
int nx, ny, num = 1; //在本题中是另外设置了一个变量num来统计最大连通分量中节点的个数
while(!Q.empty())
{
now = Q.front();
Q.pop();
for(int i = 0; i < 4; i++)
{
nx = now.x + go[i][0];
ny = now.y + go[i][1];
if(nx < 0 || nx >= h || ny < 0 || ny >= w)
continue;
if(map[nx][ny] == '#')
continue;
Node tmp;
tmp.x = nx;
tmp.y = ny;
map[nx][ny] = '#'; //已经遍历过的变为红色
Q.push(tmp);
num++;
}
}
return num;
}int main()
{
int h, w;
int sx, sy;
while(scanf("%d %d", &w, &h) && h != 0)
{
Node start;
for(int i = 0; i < h; i++)
{
scanf("%s", map[i]);
for(int j = 0; j < w; j++)
if(map[i][j] == '@')
{
start.x = i;
start.y = j;
}
}
while(!Q.empty())
Q.pop();
Q.push(start);
map[start.x][start.y] = '#';
int ans = BFS(h, w);
printf("%d\n", ans);
}
return 0;
}