有一个长方形的房间,覆盖了正方形的磁砖。每块磁砖的颜色,要么是红色,要么是黑色。一名男子站在一块黑色的磁砖上。他可以从一块磁砖移至相邻四块磁砖中的某一块。但是,他不允许在红色磁砖上移动,他只允许在黑色磁砖上移动。
编写一个程序,使得他允许重复上述的移动,判断他所能到达的黑色磁砖的数量。
输入
输入由多个数据集组成。数据集的起始行包含了两个正整数 W 和 H;W 和 H 分别是 x- 和 y- 方向的磁砖数量。W 和 H 不超过 20 。
在数据集中,还有 H 行,每行包含了 W 个字符。每个字符按如下方式表示一块磁砖的颜色。
'.' - 一块黑色的磁砖
'#' - 一块红色的磁砖
'@' - 一名男子,站在一块黑色磁砖上 (在一个数据集中,恰好出现一次)
以包含两个 0 的一行,表示输入结束。
输出
对于每个数据集,程序应当输出一行,包含他从初始磁砖所能抵达的磁砖数量 (包括初始磁砖自身)。
示例输入
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
示例输出
45 59 6 13
#include<iostream>
#include<string.h>
using namespace std;
int hang,lie;
char a[30][30];
int pan[30][30]={0};
int fang[4][2]={{1,0},{-1,0},{0,1},{0,-1}};//方位数组
int ans;
void dfs(int w,int y){//此次dfs没有判断条件,如果 到头了没有没能继续判断的位置了结束循环 ;
int ww,yy;
for(int i=0;i<4;i++){
ww=w+fang[i][0];//为什么要在引一格书最为方向,这里是做加,如果这个方向不对要重置w但如果只用w=w+..的话w的数值已变;
yy=y+fang[i][1];//所以要重设置;
if(ww<0||ww>=hang||yy<0||yy>=lie||pan[ww][yy]==1||a[ww][yy]=='#'){
continue;
}
ans++;
pan[ww][yy]=1;
dfs(ww,yy);
}
}
int main()
{
int qi1,qi2;
while(scanf("%d %d",&lie,&hang)!=EOF){
if(hang==0&&lie==0){
break;
}
ans=1;
for(int i=0;i<hang;i++){
for(int j=0;j<lie;j++){
cin >> a[i][j];
if(a[i][j]=='@'){
qi1=i,qi2=j;
}
}
}
pan[qi1][qi2]=1;//标记初始位置
dfs(qi1,qi2);
cout << ans <<endl;
memset(pan,0,sizeof(pan));//重置pan数组。
}
return 0;
}