Red and Black
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 18460 | Accepted: 9794 |
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 没什么说的,简单的递归搜索。。。//POJ 1979 Accepted 184K 16MS C++ 1052B 2013-04-11 19:54:05 #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <string> using namespace std; const int maxn = 25; string map1[maxn];//学习string的用法。 bool vis[maxn][maxn]; int n, m; int ans = 0; void search1(int row, int col) { if(row<0 || row >= m||col<0 || col>=n ||map1[row][col]=='#'||vis[row][col]) return; ++ans; vis[row][col] = true; search1(row+1, col); search1(row-1, col); search1(row, col+1); search1(row, col-1); } int main() { int row, col; while(scanf("%d%d", &n, &m) != EOF) {//先输入列再输入行。 if(m == 0&&n==0) break; memset(vis, false,sizeof(vis)); ans = 0; for(int i = 0; i < m; i++) { cin >> map1[i]; //#include <string> for(int j = 0; j < n; j++) { if(map1[i][j]=='@') { row = i; col = j; } } } search1(row, col); printf("%d\n", ans); } return 0; }