Graph breadth first traversal (BFS) and depth first traversal (DFS)

Breadth first traversal of BFS

Insert picture description here
Use the queue
, put A first
and then take A, put his adjacent point BC into the queue,
put the adjacent point of B that entered first into the queue D
queue BCD
and put it into C's adjacent point E
queue BCDE
and put D's D does not exist
Put the F
queue BCDEF of E in
this way to ensure that the order of dequeue conforms to the law of bfs (the next time the adjacent node is placed in the same order as the previous one, the first placed under the BC must be B adjacent to D and then put in C's adjacency E)
and then
get out of the queue to get ABCDEF

Depth-first traversal of DFS

Insert picture description here
Walk has been transferred back to the previous nowhere to go see if there is a point to which point did not come
ABDFEC
use the stack
A stack put
out A
into a neighbor CB
stack CB
popped out BAB
stack C
into B o Node D
stack CD
pops out DABD
stack C
puts in D's neighboring node EF
stack CEF
pops FABDF
stack CE
F has no adjacent nodes
pops out EABDFE
stack C
pops out CABDFEC to
complete the traversal

Guess you like

Origin blog.csdn.net/NuanShuTT/article/details/108402586