📜  数据结构-深度优先遍历

📅  最后修改于: 2021-01-11 10:25:02             🧑  作者: Mango


深度优先搜索(DFS)算法以深度运动方式遍历图形,并在任何迭代出现死角时使用堆栈记住要获取的下一个顶点以开始搜索。

深度优先运输

如上面的示例所示,DFS算法首先从S到A到D到G到E到B,然后到F,最后到C。它采用以下规则。

  • 规则1-访问相邻的未访问顶点。将其标记为已访问。显示它。将其推入堆栈。

  • 规则2-如果未找到相邻的顶点,则从堆栈中弹出一个顶点。 (它将弹出堆栈中没有相邻顶点的所有顶点。)

  • 规则3-重复规则1和规则2,直到堆栈为空。

Step Traversal Description
1 Depth First Search Step One Initialize the stack.
2 Depth First Search Step Two Mark S as visited and put it onto the stack. Explore any unvisited adjacent node from S. We have three nodes and we can pick any of them. For this example, we shall take the node in an alphabetical order.
3 Depth First Search Step Three Mark A as visited and put it onto the stack. Explore any unvisited adjacent node from A. Both S and D are adjacent to A but we are concerned for unvisited nodes only.
4 Depth First Search Step Four Visit D and mark it as visited and put onto the stack. Here, we have B and C nodes, which are adjacent to D and both are unvisited. However, we shall again choose in an alphabetical order.
5 Depth First Search Step Five We choose B, mark it as visited and put onto the stack. Here B does not have any unvisited adjacent node. So, we pop B from the stack.
6 Depth First Search Step Six We check the stack top for return to the previous node and check if it has any unvisited nodes. Here, we find D to be on the top of the stack.
7 Depth First Search Step Seven Only unvisited adjacent node is from D is C now. So we visit C, mark it as visited and put it onto the stack.

由于C没有任何未访问的相邻节点,因此我们不断弹出堆栈,直到找到一个具有未访问的相邻节点的节点为止。在这种情况下,没有任何东西,我们一直弹出直到堆栈为空。

要了解使用C编程语言实现此算法的方法,请单击此处