时间限制: 1 Sec 内存限制: 30 MB
题目描述
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.
输入
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.
输出
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).
样例输入
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0
样例输出
45
59
6
13
对于这个题来说使用DFS递归求解是十分合适的了,由题意可知从图中字符为‘@’的位置开始,sum为1,并且将走过的‘.’人为的修改成‘#’,然后进行上下左右的遍历,这个遍历使用递归实行,上下左右进行分别遍历,并且最大限度的到达图中为‘#’的位置,然后计次就好了。
#include<iostream>
using namespace std;
int n,m,sum;
char field[20][20];
void dfs(int x,int y){
field[x][y]='#';
if (x-1>=0&&field[x-1][y]=='.'){//向左
sum++;
dfs(x-1,y);
}
if (x+1<m&&field[x+1][y]=='.'){//向右
sum++;
dfs(x+1,y);
}
if (y-1>=0&&field[x][y-1]=='.'){//向上
sum++;
dfs(x,y-1);
}
if (y+1<n&&field[x][y+1]=='.'){//向下
sum++;
dfs(x,y+1);
}
}
int main (){
while (cin>>n>>m&&n!=0&&m!=0){
sum=1;//因为图中得到‘@’为在黑色瓷砖上的,所以这里的sum初始值为1
int a,b;
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
cin>>field[i][j];
if (field[i][j]=='@') {
a=i; b=j;//找到图中‘@’的位置,并且标识
}
}
}
dfs(a,b); //开始进行遍历
cout<<sum<<endl;
}
}