还是广度优先搜索,和1091差不多。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <queue>
using namespace std;
int main()
{
int p[21][21];
char c;
int m, n;
while (scanf("%d%d", &n, &m)!=EOF)
{
if (n==0&&m==0)
break;
int i, j;
queue<int> q;
for (i=1; i<=m; i++)
{
getchar();
for (j=1; j<=n; j++)
{
scanf("%c", &c);
if (c=='.')
p[i][j]=0;
else if (c=='@') /*出发点*/
{
q.push(i);
q.push(j);
p[i][j]=1;
}
else if (c=='#') /*标记为1即不能再走*/
p[i][j]=1;
}
}
j=0; /*计数走过的black tile*/
while (!q.empty()) /*当队列为空时所有可走的black tile都走过了*/
{
int x, y;
x = q.front();
q.pop();
y = q.front();
q.pop();
j++;
if (x-1>=1&&p[x-1][y]==0)
{
p[x-1][y]=1;
q.push(x-1);
q.push(y);
}
if(y+1<=n&&p[x][y+1]==0)
{
p[x][y+1]=1;
q.push(x);
q.push(y+1);
}
if (x+1<=m&&p[x+1][y]==0)
{
p[x+1][y]=1;
q.push(x+1);
q.push(y);
}
if(y-1>=1&&p[x][y-1]==0)
{
p[x][y-1]=1;
q.push(x);
q.push(y-1);
}
}
printf("%d\n", j);
}
return 0;
}