[Reserved] depth-first search algorithm

Reprinted from: https://blog.csdn.net/saltriver/article/category/6506969

Depth-first search (DFS, Depth First Search) is a traversal algorithm for drawing and trees. Early in the 19th century it was used to solve the maze.

For the following tree, the DFS method first starts from a root node, searches the node order is 1,2,3,4,5,6,7,8 (assuming a left branch and right branch of the left preference points branch).
Write pictures described here
DFS BFS implementation should be said that compared to similar, but the queue stack just replaced, LIFO stack having characteristics LIFO (Last Input First Output) a, DFS steps are as follows:
1, the starting point into the stack ;
2, 3 repeat the following steps until the stack is empty so far:

  • Access point from the top of the stack in the stack;
  • Identify and point adjacent to this point has not been traversed, labeled, and then put all of the stack;
  • If this point is not yet traversed neighbors, the pop-up from this point in the stack.

下面结合一个图(graph)的实例,说明DFS的工作过程和原理:
(1)将起始节点1放入栈stack中,标记为已遍历。
Write pictures described here
(2)从stack中访问栈顶的节点1,找出与节点1邻接的节点,有2,9两个节点,我们可以选择其中任何一个,选择规则可以人为设定,这里假设按照节点数字顺序由小到大选择,选中的是2,标记为已遍历,然后放入stack中。
Write pictures described here
(3)从stack中取出栈顶的节点2,找出与节点2邻接的节点,有1,3,5三个节点,节点1已遍历过,排除;3,5中按照预定的规则选中的是3,标记为已遍历,然后放入stack中。
Write pictures described here
(4)从stack中取出栈顶的节点3,找出与节点3邻接的节点,有2,4两个节点,节点2已遍历过,排除;选中的是节点4,标记为已遍历,然后放入stack中。
Write pictures described here
(5)从stack中取出栈顶的节点4,找出与节点4邻接的节点,有3,5,6三个节点,节点3已遍历过,排除;选中的是节点5,标记为已遍历,然后放入stack中。
Write pictures described here
(6)从stack中取出栈顶的节点5,找出与节点5邻接的节点,有2,4两个节点,节点2,4都已遍历过,因此节点5没有尚未遍历的邻接点,则将此点从stack中弹出。
Write pictures described here
(7)当前stack栈顶的节点是4,找出与节点4邻接的节点,有3,5,6三个节点,节点3,5都已遍历过,排除;选中的是节点6,标记为已遍历,然后放入stack中。
Write pictures described here
(8)当前stack栈顶的节点是6,找出与节点6邻接的节点,有4,7,8三个节点,4已遍历,按照规则选中的是7,标记为已遍历,然后放入stack中。
Write pictures described here
(9) of the current node stack top of the stack is 7, and 7 to find adjacent nodes, only node 6, has been traversed, so no neighbors yet traversed, the node 7 from the stack of pop.
Write pictures described here
(10) the current node is a stack top of the stack 6, and to identify the adjacent node 6, the node has been traversed 7,8,7, 8 thus the nodes placed in the stack.
Write pictures described here
(11) the current node is a stack top of the stack 8, 8 adjacent to identify the node, the node 1,6,9,1,6 has been traversed, so in the node 9 into the stack.
Write pictures described here
(12) the current node stack top of the stack 9 is not yet traversed adjacent point, node 9 will pop up, and so on, the remaining nodes in the stack are not adjacent point 8,6,4,3,2,1 yet traversed, It will pop up, and finally the stack is empty.
(13) DFS traversal completion.

Guess you like

Origin www.cnblogs.com/toooney/p/10991629.html