现在的位置: 首页 > 综合 > 正文

深度优先搜索

2014年01月01日 ⁄ 综合 ⁄ 共 2743字 ⁄ 字号 评论关闭

深度优先搜索 (Depth-First Traversal)

深度优先搜索的思想是尽可能深的搜索图,在<<算法艺术与信息学竞赛>>一书中提到:随机搜索就像是在慌乱之中找东西,因为你并不知道东西在哪,广度优先搜索则像是你的眼镜掉在地上之

深度优先搜索 (Depth-First Traversal)
深度优先搜索的思想是尽可能深的搜索图,在<<算法艺术与信息学竞赛>>一书中提到:随机搜索就像是在慌乱之中找东西,因为你并不知道东西在哪,广度优先搜索则像是你的眼镜掉在地上之后,你肯定会先摸最近的一片区域,而深度优先搜索则像你在走迷宫,你不可能有分身术同时站在每一个点上,只能沿着一条路走到底,如果碰壁了,则退回来再搜索下一个可能的路径.深度优先遍历类似于树的前序遍历。采用的搜索方法的特点是尽可能先对纵深方向进行搜索。
  例如对于以下一个树:
          1
        2   3
      4   5   6
深度优先的策略是1->2->4->退后一步->5->退后一步->退后一步->3->6->结束
而广度优先则是第一次:1->2->3第2次:4->5->6

从深度优先的策略上看就知道深搜一般是用递归来实现;深度优先搜索的框架很简单:
void Dfs ( int n )
{
     if ( 满足结束条件,即搜索到终点 )
         return ;
     else
         Dfs ( n + 1 );
}
深搜的框架是如此简单,但是它可能有很多变种,一般用来搜索图,那么传的参数就不可能只有一个那么简单,下面用一个简单的例子来说明:

PKU ACM 网页原题:1562 Oil Deposits
Description
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
Input
The input contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket.
Output
are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
Sample Input
1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5
****@
*@@*@
*@**@
@@@*@
@@**@
0 0
Sample Output
0
1
2
2
题目的意思就是在给出的图中@代表有石油,*代表没有石油,而在一个有石油的地方它的周围8个方向的地方如果也有石油,那么这2块石油是属于一块的,给出图,问图中有几块石油田.
如图1: 一个1 * 1 大小的图,只有一个*,就是没有石油.
图2: 3 * 5 大小的图中因为:
@ @
 @
@ @
是连成一块的,所以图中只有一个油田
同理第3个图有3个油田.
解题方法:
采用深度优先搜索策略,对给出的图中一旦出现一个@则对其8个方向进行搜索,并对搜索过的@标记,直到一次搜索结束则油田总数加一,最后的总数即为所求的石油的方块数。
代码如下:

  
本篇文章来源于:开发学院 http://edu.codepub.com   原文链接:http://edu.codepub.com/2009/1023/16653.php

【上篇】
【下篇】

抱歉!评论已关闭.