深度优先搜索(Depth-First Search)是搜索的手段之一,它从某个状态(节点)开始,不断地转移状态(节点)直到无法转移,然后回退回上一状态,继续转至其他状态。
如此不断重复,直到找到最终的解。例如求解数独,根据深度优先搜索的特点,采用递归函数实现比较简单合理。
这篇博文由于水平有限且为学习笔记,简单的写一下DFS入门知识,归纳总结留待下一篇DFS相关博文。
以经典的POJ 2386为例子。就是求出图中有几个水洼(w代表积水,.代表没有积水)。
此题较为简单,我们对图整个进行遍历,一旦发现了’W‘,我们进入搜索函数,对周边的额八个方向整体进行遍历,并同步修改图,当我们遍历完整个图的时候,我们也就计算出来了块的个数。
也就是说,有几次由函数内开始的dfs就有几处水洼。
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.
OutputLine 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
Hint
#include<iostream>
#include<cstdio>
#include<cstdlib>
#define N 105
using namespace std;
int n,m;
char map[N][N];
int count=0;
void dfs(int x,int y)
{
map[x][y]='.';
for(int dx= -1;dx<=1;dx++){
for(int dy=-1;dy<=1;dy++){
//向x方向移动dx,向y方向移动dy,移动结果为(nx,ny)
int nx= x+dx;
int ny= y+dy;
//判断该点是否在园内,以及是否有积水
if(0<=nx&&nx<n&&0<=ny&&ny<=n&&map[nx][ny]=='w') dfs(nx,ny);
}
}
return ;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(map[i][j]=='W')
{
map[i][j]='.';
count++;
dfs(i,j);
}
}
}
cout<<count<<endl;
return 0;
}