算法学习笔记(六)------深度优先搜索(DFS)

深度优先搜索(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.
    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
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;  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值