According to Wikipedia's pseudo-code implementation:
Breadth First BFS:
Using queues , collections
Mark initial node has been found, put into queue
Each loop pops a node from the queue.
Put all connected nodes of the node in the queue and mark the discovery
Through the queue, open all the doors of the maze intersection, go in through a door, open the door inside, and then go back to the front door.
1 """2 procedure BFS (g,v) is3 Let Q is a queue4 Q.enqueue (v)5 Label V as discovered6 While Q isn't empty7 V←q.dequeue ()8 procedure (v)9 For all edges from-V to W-g.adjacentedges (v) doTen If W is not labeled as discovered One Q.enqueue (W) A label W as discovered - """ - defprocedure (v): the Pass - - defBFS (g,v0): - """Breadth First Search""" +Q, s =[], set () - q.extend (V0) + S.add (V0) A whileQ:#when the queue Q is not empty atv =q.pop (0) - procedure (v) - forWinchG[V]:#all neighboring points W of Vertex v in Figure G - ifW not inchS#if vertex w is not found - Q.extend (W) -S.add (W)#record W has been found
Depth-First Dfs
Using stacks , collections
Initial node into the stack.
Each round of loops pops a node from the stack and marks the discovery
Place all nodes connected to the queue for each popup node.
Through the structure of the stack, one step at a deep excavation
1 """"2 Pseudocode[edit]3 input:a graph G and A Vertex V of G4 5 output:all vertices reachable from v labeled as discovered6 7 A recursive implementation of DFS:[5]8 9 1 Procedure DFS (g,v):Ten 2 Label V as discovered One 3 for all edges from V to W in G.adjacentedges (v) do A 4 If vertex w isn't labeled as discovered then - 5 recursively call DFS (G,W) - A non-recursive Implementation of Dfs:[6] the - 1 Procedure dfs-iterative (g,v): - 2 Let S be a stack - 3 S.push (v) + 4 while S isn't empty - 5 V = s.pop () + 6 If V is not labeled as discovered: A 7 Label V as discovered at 8 for all edges from V to W in G.adjacentedges (v) do - 9 S.push (W) - """ - - defDFS (g,v0): -S = [] in s.append (V0) -Label =set () to whileS: +v =S.pop () - ifV not inchLabel: the Label.add (v) * procedure (v) $ forWinchG[v]:Panax NotoginsengS.append (W)
Python data structures and algorithms-the breadth-first and depth-first algorithm of graphs