There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and Hare the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.
'.' --- a black tile
'#' --- a red tile
'@' --- a man on a black tile(appears exactly once in a data set)
The end of the input is indicated by a line consisting of two zeros.
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
45
59
6
13
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <bits/stdc++.h> using namespace std; int main() { int m[4][2]; m[0][0]=-1; m[0][1]=0; m[1][0]=1; m[1][1]=0; m[2][0]=0; m[2][1]=-1; m[3][0]=0; m[3][1]=1; /// 上下左右四种位移 int h,w,flag[25][25]; while(~scanf("%d%d",&h,&w)&&h&&w) { int a,b,sum=1; char ch[25][25]; for(int i=1;i<=w;i++) { getchar(); for(int j=1;j<=h;j++) { scanf("%c",&ch[i][j]); if(ch[i][j]=='@') a=i,b=j; /// 记录人的位置,即起点 } } memset(flag,0,sizeof(flag)); flag[a][b]=1; queue <int> x,y; x.push(a),y.push(b); while(!x.empty()&&!y.empty()) { for(int i=0;i<4;i++) { a=x.front()+m[i][0]; b=y.front()+m[i][1]; if(a>0&&a<=w&&b>0&&b<=h //如果点在范围内,且 &&ch[a][b]!='#'&&!flag[a][b])//位于没走过的黑瓷砖 x.push(a), y.push(b), sum++; //放入队列 否则忽略 flag[a][b]=1; } x.pop(), y.pop(); } printf("%d ",sum); } return 0; }