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.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are 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.
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.
Output
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).
Sample Input
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 11 9 .#......... .#.#######. .#.#.....#. .#.#.###.#. .#.#..@#.#. .#.#####.#. .#.......#. .#########. ........... 11 6 ..#..#..#.. ..#..#..#.. ..#..#..### ..#..#..#@. ..#..#..#.. ..#..#..#.. 7 7 ..#.#.. ..#.#.. ###.### ...@... ###.### ..#.#.. ..#.#.. 0 0
Sample Output
45 59 6 13
BFS
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 int lenx,leny; 7 char a[25][25]; 8 struct lll 9 { 10 int x,y; 11 }qidian; 12 int TM=0; 13 int c[25][25]; 14 int b[4][2]={1,0,-1,0,0,1,0,-1}; 15 void dfs(int y,int x) 16 { 17 if(TM>lenx*leny) 18 return ; 19 20 if(y<1||x<1||x>lenx||y>leny) 21 return ; 22 23 if(a[y][x]=='#'||c[y][x]!=0) 24 return ; 25 c[y][x]=++TM; 26 for(int i=0;i<4;i++) 27 { 28 dfs(y+b[i][1],x+b[i][0]); 29 } 30 } 31 int main() 32 { 33 while(cin>>lenx>>leny) 34 { 35 if(lenx==0&&leny==0) 36 break; 37 memset(a,0,sizeof(a)); 38 memset(c,0,sizeof(c)); 39 for(int i=1;i<=leny;i++) 40 { 41 for(int j=1;j<=lenx;j++) 42 { 43 cin>>a[i][j]; 44 if(a[i][j]=='@') 45 { 46 qidian.y=i; 47 qidian.x=j; 48 } 49 } 50 } 51 TM=0; 52 dfs(qidian.y,qidian.x); 53 cout<<TM<<endl; 54 } 55 return 0; 56 }