龙空技术网

黄哥Python:图深度优先算法(dfs)

跟黄哥学编程 254

前言:

而今各位老铁们对“全排列dfs算法”都比较注重,你们都需要知道一些“全排列dfs算法”的相关文章。那么小编同时在网络上网罗了一些对于“全排列dfs算法””的相关资讯,希望各位老铁们能喜欢,大家快快来了解一下吧!

深度优先搜索算法(英语: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)

黄哥所写的代码,迭代实现。

递归实现。

请看西瓜视频播放地址。

标签: #全排列dfs算法