DFS也叫深度优先遍历,是一种可以优化的暴力搜索方法,可用于图的遍历、树的遍历、走迷宫等等。这一小节,我们实现一下用DFS走迷宫。DFS可以找到一条出迷宫的路,但是不一定是最短的,这点需要注意。在走迷宫问题上,DFS可以判断该迷宫是否有解以及找出其中一个解,也可以判断一个迷宫有多少连通区域。
接下来让我们看看poj上第2386号问题:
Description
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (’.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John’s field, determine how many ponds he has.
Input
-
Line 1: Two space-separated integers: N and M
-
Lines 2…N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
Output
- Line 1: The number of ponds in Farmer John’s field.
Sample Input
10 12
W…WW.
.WWW…WWW
…WW…WW.
…WW.
…W…
…W…W…
.W.W…WW.
W.W.W…W.
.W.W…W.
…W…W.
Sample Output
3
接下来请看中文翻译:
这个问题看似不是走迷宫,确跟走迷宫近乎一样。我们可以从园子左上角开始遍历,一发DFS,我们把所有能遍历到的’W’置为’.’ 。看至少多少次DFS能将遍历完所有,这个次数就是水洼个数。
//
// Created by 程勇 on 2018/10/6.
//
#include <iostream>
using namespace std;
const int maxn = 101, maxm = 101;
int N, M;
char filed[maxn][maxm];
void dfs(int x, int y)
{
filed[x][y] = '.'; // 将遍历到的点置为'.'
// 9个方向循环遍历(包含本身)
for(int dx=-1; dx<=1; dx++)
{
for(int dy=-1; dy<=1; dy++)
{
int nx = x+dx;
int ny = y+dy;
if(0<=nx && nx<N && 0<=ny && ny<M && filed[nx][ny]=='W')
dfs(nx, ny);
}
}
}
int main()
{
cin >> N >> M;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
cin >> filed[i][j];
}
}
int res = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if(filed[i][j] == 'W')
{
dfs(i, j);
res++;
}
}
}
cout << res << endl;
return 0;
}