题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1312
题记:用广度优先搜索和队列的方式把所有格子走一步。
#include<bits/stdc++.h>
using namespace std;
#define check(x,y)(x<wx&&x>=0&&y>=0&&y<hy)//判断是否在room中
char room[25][25];
int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
//左上角坐标为(0,0),向左,向上,向右,向下
int wx,hy,num;
struct node{
int x,y;
};
void bfs(int dx,int dy){
num=1;//起点图块也算一个
queue<node>q;
node start,next;
start.x=dx;
start.y=dy;
q.push(start);//起点入队
while(!q.empty()){//当队列不为空时
start=q.front();//返回队首元素
q.pop();//删除队首元素
//cout<<"out"<<start.x<<start.y<<endl;(打印出队列情况,用于验证)
for(int i=0;i<4;i++){//四个方向逐一搜索
next.x=start.x+dir[i][0];
next.y=start.y+dir[i][1];
if(check(next.x,next.y)&&room[next.x][next.y]=='.'){
//判断当前位置是否在room中且是黑色图块(即'.')
room[next.x][next.y]='#';//入队后标记已经处理过
num++;//黑色图块加一
q.push(next);//进队
}
}
}
}
int main(){
int x,y,dx,dy;
while(cin>>wx>>hy){
if(wx==0&&hy==0)
break;
for(y=0;y<hy;y++){
for(x=0;x<wx;x++){
cin>>room[x][y];
if(room[x][y]=='@'){//记录起点位置
dx=x;
dy=y;
}
}
}
num=0;
bfs(dx,dy);
cout<<num<<endl;
}
return 0;
}