Red and Black
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 25024 | Accepted: 13511 |
Description
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 这道题我用的是dfs算法,不断地找周围的'.',找到一个后就标记位'#',开始要记得获得初始的位置。 我的代码: #include<iostream> #include<cstdio> #include<algorithm> #include<string> #include<cstring> #include<cstdlib> #include<set> #include<map> #include<vector> #include<iomanip> const int MAX=200; using namespace std; char arr[MAX][MAX]; int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; int w,h; int sum=1; int dfs(int x,int y) { arr[x][y]='#'; for(int k=0;k<4;k++) { int dx=x+dir[k][0]; int dy=y+dir[k][1]; if(0<dx&&dx<=h&&0<dy&&dy<=w&&arr[dx][dy]=='.') { sum++; dfs(dx,dy); } } return 0; } int main() { while(scanf("%d%d",&w,&h)&&w&&h) { int beg,end; for(int i=1;i<=h;++i) { for(int j=1;j<=w;++j) { cin>>arr[i][j]; if(arr[i][j]=='@') { beg=i; end=j; } } } dfs(beg,end); printf("%d\n",sum); sum=1; } return 0; } 写这个代码中遇见的一些问题: 1、无故地提醒我count是ambiguous的,不知道这是为什么,然后我就把count改成了sum了; 2、记得每次要把sum重新初始化,所以我在最后加入了sum=1这句; 3、开始敲的时候,老是分不清w,h,所以行和列数,我搞错了。 欢迎大家一起交流(*^__^*) 嘻嘻……