python数据结构与算法——图的广度优先和深度优先的算法
根据维基百科的伪代码实现:
广度优先BFS:
使用队列,集合
标记初始结点已被发现,放入队列
每次循环从队列弹出一个结点
将该节点的所有相连结点放入队列,并标记已被发现
通过队列,将迷宫路口所有的门打开,从一个门进去继续打开里面的门,然后返回前一个门处
1 """ 2 procedure BFS(G,v) is 3 let Q be a queue 4 Q.enqueue(v) 5 label v as discovered 6 while Q is not empty 7 v ← Q.dequeue() 8 procedure(v) 9 for all edges from v to w in G.adjacentEdges(v) do 10 if w is not labeled as discovered 11 Q.enqueue(w) 12 label w as discovered 13 """ 14 def procedure(v): 15 pass 16 17 def BFS(G,v0): 18 """ 广度优先搜索 """ 19 q, s = [], set() 20 q.extend(v0) 21 s.add(v0) 22 while q: # 当队列q非空 23 v = q.pop(0) 24 procedure(v) 25 for w in G[v]: # 对图G中顶点v的所有邻近点w 26 if w not in s: # 如果顶点 w 没被发现 27 q.extend(w) 28 s.add(w) # 记录w已被发现
深度优先DFS
使用 栈,集合
初始结点入栈
每轮循环从栈中弹出一个结点,并标记已被发现
对每个弹出的结点,将其连接的所有结点放到队列中
通过栈的结构,一步步深入挖掘
1 """" 2 Pseudocode[edit] 3 Input: A graph G and a vertex v of G 4 5 Output: All vertices reachable from v labeled as discovered 6 7 A recursive implementation of DFS:[5] 8 9 1 procedure DFS(G,v): 10 2 label v as discovered 11 3 for all edges from v to w in G.adjacentEdges(v) do 12 4 if vertex w is not labeled as discovered then 13 5 recursively call DFS(G,w) 14 A non-recursive implementation of DFS:[6] 15 16 1 procedure DFS-iterative(G,v): 17 2 let S be a stack 18 3 S.push(v) 19 4 while S is not empty 20 5 v = S.pop() 21 6 if v is not labeled as discovered: 22 7 label v as discovered 23 8 for all edges from v to w in G.adjacentEdges(v) do 24 9 S.push(w) 25 """ 26 27 def DFS(G,v0): 28 S = [] 29 S.append(v0) 30 label = set() 31 while S: 32 v = S.pop() 33 if v not in label: 34 label.add(v) 35 procedure(v) 36 for w in G[v]: 37 S.append(w)