Time limit:1000ms
Memory limit:30000k
Description
There is a rectangular room and covered with square tiles. Each tile are colored either red or black. A mans is standing on a black tile. From a tile, he can move to one of the four adjacent tiles. But he can's ' t move on red tiles, and he can move in black tiles.
Write a program to count the number of black tiles which and 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 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 mans on a black tile (appears exactly once in a data set)
The end of the "input is indicated by a" consisting of two zeros.
Output
For each data set, your program should output a-line which contains the number of tiles to the the initial (including itself).
Sample Input
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#.. #.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#.. @#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
.. #.. #.. #..
.. #.. #.. #..
.. #.. #.. ###
.. #.. #.. #@.
.. #.. #.. #..
.. #.. #.. #..
7 7
.. #.#..
.. #.#..
###.###
...@...
###.###
.. #.#..
.. #.#..
0 0
Sample Output
45
59
6
13
Source
Japan Domestic
A few days without a problem, first take the road water heat hot hands.
Complete code:
/*16ms,388kb*/
#include <cstdio>
#include <cstring>
char grid[25][25];
BOOL vis[25][25];
int cnt, x, y;
void Dfs (int i, int j)
{
if (grid[i][j] = = ' # ' | | vis[i][j]) return;
VIS[I][J] = true;
++cnt;
DFS (I-1, j); DFS (i + 1, j); DFS (i, j-1); DFS (I, j + 1);
}
int main ()
{
int i, J, xx, yy;
while (scanf ("%d%d\n", &x, &y), x)
{
memset (grid, ' # ', sizeof (GRID));
for (i = 1; I <= y; ++i)
{for
(j = 1; j <= x; ++j)
{
Grid[i][j] = GetChar ();
if (grid[i][j] = = ' @ ')
xx = i, yy = j;
}
GetChar ();
}
memset (Vis, 0, sizeof (VIS));
CNT = 0;
DFS (xx, yy);
printf ("%d\n", CNT);
}
return 0;
}
Author Signature: CSDN blog Synapse7
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/