这是一道非常中规中矩的题目,没有太多值得说的地方。不过写的时候发现对很多基础概念的理解不是很清晰,浪费了很多时间。
#include<stdio.h>
#include<queue>
using namespace std;
struct node
{
int x,y;
};
char map[25][25];
int dir[4][2]={1,0, 0,1, 0,-1, -1,0};
int m,n,ans;
int x,y;
int judge(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]=='.')
return 1;
return -1;
}
int bfs()
{
int i;
node cur,next;
queue<node>q;
ans=1;
cur.x=x;
cur.y=y;
map[x][y]='#';
q.push(cur);
while(!q.empty())
{
cur=q.front();
q.pop();
for(i=0;i<4;i++)
{
next.x=x=cur.x+dir[i][0];
next.y=y=cur.y+dir[i][1];
if(judge(x,y)==1)
{
ans++;
map[x][y]='#';
q.push(next);
}
}
}
return ans;
}
int main()
{
int i,j;
while(scanf("%d%d",&m,&n),m||n)
{
getchar();
for(i=0;i<n;i++)
{
if(i!=0)
getchar();
for(j=0;j<m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='@')
{
x=i;
y=j;
}
}
}
ans=bfs();
printf("%d\n",ans);
}
return 0;
}