DFS搜索

DFS搜索

  DFS(深度搜索)是一种基础的穷竭搜索方式,从某个状态开始,一直不停的转移的状态直至无法转移,然后回溯到上一步的状态,然后反复进行以上行为,直至得到最终答案,或者遍历完所有情况,发现无解。DFS主要以递归的方式实现,该方法是一种偏向于暴力的搜索方法,但也可以通过巧妙的剪枝处理,降低其时间复杂度。

  老规矩 直接上例题:POJ 3009;

  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
  该题目大意就是说一个人从“@”标记的点开始移动,他可以移动到“.”点上,但是“#”上是禁止移动的,求其能移动到的地方共有多少处。(人只能上,下,左,右,四个方向进行移动,不能沿着对角线移动);

 该题的思路很简单,就是从起点开始进行DFS搜索,直至遍历完所有的点即可。

#include 
#include 
using namespace std;
#define Max_n 22
char room[Max_n][Max_n];
int W, H;
int res ;
int n[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};  //该数组主要来用来模拟人的移动。
void dfs (int x, int y)
{
    room[x][y] = '#';  //将所有已经遍历的点变为不可通过的点,防止重复统计。
    int nx, ny;
    for (int i = 0; i < 4; i ++)
    {
        nx = x + n[i][0];
        ny = y + n[i][1];
       // printf("%d %d\n", nx, ny);
        if(0 <= nx && nx < H && 0 <= ny && ny < W && room[nx][ny] == '.') {   //防止越界操作。
            dfs (nx, ny);
            res ++;  //每次移动结束,回退的时候,就对记录的变量进行一次自增操作。
        }
    }


}
void solve ()
{
    for (int i = 0; i < H; i ++)
        for (int j = 0; j < W; j ++) {
            if (room[i][j] == '@') {
                dfs(i, j);
                res ++;
            }
        }
    printf("%d\n", res);
}
int main()
{
    while(~scanf("%d%d", &W, &H)) {
        if (W == 0 && H == 0) continue;
        for (int i = 0; i < H; i ++)
            scanf("%s", &room[i][0]);
            res = 0;
            solve ();

    }

    return 0;
}


你可能感兴趣的:(搜索)