在有向图上执行DFS和BFS

时间:2013-04-28 08:30:18

标签: algorithm graph depth-first-search breadth-first-search

假设我们有一个图表,如:

graph

如果你想要一个从0到5的路径,如果我们在这个图上执行DFS和BFS,我们将以什么顺序访问节点(假设始终首先推送最低元素)。我无法概念化算法如何适用于具有周期的图形,我希望有人可以概述每个图形的过程。

1 个答案:

答案 0 :(得分:4)

用于处理循环的常用技术是具有已访问过的顶点集。在将顶点推送到队列/堆栈之前,请检查它是否已被访问。如果不执行任何操作,则从将其添加到访问集开始,然后继续遍历图。

从上到下堆叠。

DFS:

empty stack
visiting 0: stack: 2, 1, visited: 0
visiting 2: stack: 5, 3, 1 visited: 0, 2
visiting 5: stack: 4, 3, 1 visited: 0, 2, 5
visiting 4: stack: 3, 2, 3, 1 visited: 0, 2, 4, 5
visiting 3: stack: 4, 2, 3, 1 visited: 0, 2, 3, 4, 5
visiting 4: (nothing to do) - stack: 2, 3, 1 visited: 0, 2, 3, 4, 5
visiting 2: (nothing to do) - stack: 3, 1 visited: 0, 2, 3, 4, 5
visiting 3: (nothing to do) - stack: 3, 1 visited: 0, 2, 3, 4, 5
visiting 1: stack: 3, 0 visited: 0, 1, 2, 3, 4, 5
visiting 3: (nothing to do) - stack: 1 visited: 0, 1, 2, 3, 4, 5
visiting 1: (nothing to do) - stack empty visited: 0, 1, 2, 3, 4, 5
DONE

以类似的方式为BFS做。