深度优先搜索算法(英语:Depth-First-Search,DFS)是一种用于遍历或搜索树或图的算法。沿着树的深度遍历树的节点,尽可能深的搜索树的分支。当节点v的所在边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进行直到所有节点都被访问为止。属于盲目搜索。
深度优先搜索是图论中的经典算法,利用深度优先搜索算法可以产生目标图的相应拓扑排序表,利用拓扑排序表可以方便的解决很多相关的图论问题,如最大路径问题等等。因发明“深度优先搜索算法”,约翰·霍普克洛夫特与罗伯特·塔扬在1986年共同获得计算机领域的最高奖:图灵奖。
伪代码(Pseudocode):
Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered
A recursive implementation of DFS:
procedure DFS(G, v) is
label v as discovered
for all directed edges from v to w that are in G.adjacentEdges(v) do
if vertex w is not labeled as discovered then
recursively call DFS(G, w)
The order in which the vertices are discovered by this algorithm is called the lexicographic order.
A non-recursive implementation of DFS with worst-case space complexity 。
procedure DFS-iterative(G, v) is
let S be a stack
S.push(v)
while S is not empty do
v = S.pop()
if v is not labeled as discovered then
label v as discovered
for all edges from v to w in G.adjacentEdges(v) do
S.push(w)
黄哥所写的代码,迭代实现。
![53056044f8b6771377c99a1aa3388567.png](https://i-blog.csdnimg.cn/blog_migrate/c82a0b6d6f03e3ea63d745811173bbe0.jpeg)
递归实现。
![fd552856dc733564797a17e8462f656b.png](https://i-blog.csdnimg.cn/blog_migrate/3bc09dac678c0e72d588816fcd2a49d5.jpeg)
请看视频讲解。
![7680ec3dcdb89c5ed10f6e10dec8a36b.png](https://i-blog.csdnimg.cn/blog_migrate/9e0d77187cf2e537f1089d5ce7f740b4.png)