题目(http://poj.org/problem?id=1979)
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.
输入
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.
输出
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?
题目让求人从‘@’出发,途中经过的‘.’的个数,再通过输入样例,大致就能分析出这道题和求图的连通块的个数类似,但这题只有一个块,求的是该块内‘.’的个数。
怎么用DFS?(搜索讲解,别人的感觉讲的还可以。https://blog.csdn.net/whereisherofrom/article/details/78921973)
DFS算法是图的遍历的一种,这道题怎么和图联系起来呢?可以这样想,图的每个结点代表输入中的r,c(第r行,第c列)所确定的符号是什么,而图的边代表方向(如下图,图比较简陋,大致就是这样),DFS求解该问题就是在四个方向上分别DFS,遇到‘.’cnt++,到头或遇到‘#’就换方向搜。
代码:
#include<iostream>
using namespace std;
struct Point {
int x;
int y;
};
char mapp[22][22];
int visit[22][22];
int H, W;
Point dir[4] = { {-1,0 }, { 0,1 }, { 1,0 }, { 0,-1 } };
void DFS(int r, int c,int &cnt) {
if (r < 0 || r >= H || c < 0 || c >= W)return ; //出界返回
visit[r][c] = 1; //标记当前位置,表示已走过,cnt++
cnt++;
for (int i = 0; i < 4; i++) { //四个方向,代表图的四条边
if (!visit[r + dir[i].x][c + dir[i].y])
{
DFS(r + dir[i].x, c + dir[i].y,cnt); //访问当前结点
}
}
}
int main() {
while (cin >> W >> H&&W&&H) {
int r = 0, c = 0;
int sum = 0;
memset(visit, 0, sizeof(visit));
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
cin >> mapp[i][j];
if (mapp[i][j] == '@') {
r = i;
c = j;
}
if (mapp[i][j] == '#') {
visit[i][j] = 1;
}
}
}
DFS(r, c,sum);
cout << sum << endl;
}
return 0;
}