题目:
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.
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.
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
题目链接:http://poj.org/problem?id=1979
题解:
1、@位置为起始点,只能上下左右四个方向可以走,“.”表示通路,“#”表示墙,统计能走到的“.”通路的个数;
2、根据题意很容易的就想到DFS算法,从起点遍历它四个方向的位置,再通过递归的思想一次遍历下去;
3、二维数组存储整个矩阵,找到起始点“@”,在从起始点开始遍历,调用敲写dfs函数;
4、子函数中,判断传入的x[ i ][ j ]点是否为通路,是则用计数器++,再用for循环从四个方向遍历;
5、值得注意的是,每次遍历都要保证未越界。
代码:
#include<cstdio>
using namespace std;
int t[4][2]={1,0,0,-1,-1,0,0,1};
char x[25][25];
int ans;
int m,n;
void dfs(int i,int j){
x[i][j]='#';
ans++;
//printf("%d %d\n",i,j);
for(int k=0;k<4;k++){
int di,dj;
di=i+t[k][0];
dj=j+t[k][1];
if(di>=0 && di<m &&dj>=0 && dj<n && x[di][dj]=='.')
dfs(di,dj);
}
}
int main()
{
while(~scanf("%d%d",&n,&m)){
ans=0;
if(m==0&&n==0)
break;
for(int i=0;i<m;i++)
scanf("%s",x[i]);
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(x[i][j]=='@')
{
dfs(i,j);
break;
}
}
}
printf("%d\n",ans);
}
return 0;
}