深度优先搜索(Depth-First-Search)
来源:互联网 发布:pplive网络电视2015 编辑:程序博客网 时间:2024/05/26 02:21
个人觉得深度优先搜索理解起来比广度优先搜索会难一点。
广度优先搜索直接寻找与当前节点最接近的所有节点,而深度优先搜索则有回溯的过程,采用的搜索方法的特点是尽可能先对纵深方向进行搜索。
过程
设x是当前被访问顶点,在对x做过访问标记后,选择一条从x出发的未检测过的边(x,y)。若发现顶点y已访问过,则重新选择另一条从x出发的未检测过的边,否则沿边(x,y)到达未曾访问过的y,对y访问并将其标记为已访问过;然后从y开始搜索,直到搜索完从y出发的所有路径,即访问完所有从y出发可达的顶点之后,才回溯到顶点x,并且再选择一条从x出发的未检测过的边。上述过程直至从x出发的所有边都已检测过为止。此时,若x不是源点,则回溯到在x之前被访问过的顶点;否则图中所有和源点有路径相通的顶点(即从源点可达的所有顶点)都已被访问过,若图G是连通图,则遍历过程结束,否则继续选择一个尚未被访问的顶点作为新的顶点,继续遍历。
代码(代码引用自百度)
template <int max_size>void Digraph<max_size> :: depth_first(void (*visit)(Vertex &)) const
/* Post: The function *visit has been performed at each vertex of the Digraph in depth-first order.
Uses: Method traverse to produce the recursive depth-first order. */
{
bool visited [max_size];
Vertex v;
for (all v in G) visited [v] = false;
for (all v in G) if (!visited [v])
traverse (v, visited, visit);
}
template <int max_size>
void Digraph<max_size>::traverse(Vertex &v, bool visited[ ],void (*visit)(Vertex &)) const
/* Pre: v is a vertex of the Digraph.
Post: The depth-first traversal, using function *visit, has been completed for v and for all vertices that can be reached from v.
Uses: traverse recursively. */
{
Vertex w;
visited [v] = true;
(*visit) (v);
for (all w adjacent to v)
if (!visited [w])
traverse (w, visited, visit);
}
深度优先搜索用一个数组存放产生的所有状态。
(1) 把初始状态放入数组中,设为当前状态;
(2) 扩展当前的状态,产生一个新的状态放入数组中,同时把新产生的状态设为当前状态;
(3) 判断当前状态是否和前面的重复,如果重复则回到上一个状态,产生它的另一状态;
(4) 判断当前状态是否为目标状态,如果是目标,则找到一个解答,结束算法。
(5) 如果数组为空,说明无解。
0 0
- 深度优先搜索(Depth-First-Search)
- 深度优先搜索(Depth-First-Search,DFS)
- 深度优先搜索算法(Depth first search)
- 深度优先搜索算法(Depth-First-Search)
- 图的深度优先搜索(Depth First Search,DFS)
- 5.3.2 深度优先搜索(Depth-First-Search,DFS)
- DFS-深度优先搜索(Depth First Search)—1
- [数据结构]深度优先搜索算法(Depth-First-Search,DFS)
- TensorFlow中的深度优先搜索(Depth-first search, DFS)
- 图的深度优先搜索/Depth-first search/C++
- 图的深度优先搜索(Depth First Search)
- 深度优先搜索Depth-first search (DFS) for undirected graphs
- DFS --- Depth First Search 深度优先搜索算法
- 图的深度优先搜索/Depth-first search/C++
- 深度优先搜索DFS(depth first search),拓扑排序
- 图的深度优先搜索/Depth-first search/C++
- 穷竭搜索之深度优先搜索DFS(Depth-First Search)
- (Basic algorithm学习笔记)《基础算法四》- 深度优先搜索(Depth First Search,DFS )
- 去除csv文件单元格内的逗号
- 网页设计的几大趋势
- 【Mac版】串口开发搭建环境步骤
- Leap Motion的环境配置(使用c#)
- java内部类学习笔记
- 深度优先搜索(Depth-First-Search)
- Leetcode: Remove Linked List Elements
- linux常用命令二之权限,搜索与帮助命令
- IIS下安装PHP
- Android APK安装常见错误列表
- 链表操作
- [ios]the file couldn't be opened because you don't have permission to view it
- 格雷码 Gray
- nginx源码分析1———进程间的通信机制五(文件锁)