Python數據結構與算法之圖的廣度優先與深度優先搜索算法示例

本文實例講述了Python數據結構與算法之圖的廣度優先與深度優先搜索算法。分享給大家供大家參考,具體如下:

Python數據結構與算法之圖的廣度優先與深度優先搜索算法示例

廣度優先BFS:

使用隊列,集合

標記初始結點已被發現,放入隊列

每次循環從隊列彈出一個結點

將該節點的所有相連結點放入隊列,並標記已被發現

通過隊列,將迷宮路口所有的門打開,從一個門進去繼續打開裡面的門,然後返回前一個門處

<code>"""
procedure BFS(G,v) is
let Q be a queue
Q.enqueue(v)
label v as discovered
while Q is not empty
v ← Q.dequeue()
procedure(v)
for all edges from v to w in G.adjacentEdges(v) do
if w is not labeled as discovered
Q.enqueue(w)
label w as discovered
"""
def procedure(v):
pass
def BFS(G,v0):
""" 廣度優先搜索 """
q, s = [], set()
q.extend(v0)
s.add(v0)
while q: # 當隊列q非空
v = q.pop(0)
procedure(v)
for w in G[v]: # 對圖G中頂點v的所有鄰近點w

if w not in s: # 如果頂點 w 沒被發現
q.extend(w)
s.add(w) # 記錄w已被發現
/<code>

深度優先DFS

使用 棧,集合

初始結點入棧

每輪循環從棧中彈出一個結點,並標記已被發現

對每個彈出的結點,將其連接的所有結點放到隊列中

通過棧的結構,一步步深入挖掘

<code>""""
Pseudocode[edit]
Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered
A recursive implementation of DFS:[5]
1 procedure DFS(G,v):
2 label v as discovered
3 for all edges from v to w in G.adjacentEdges(v) do
4 if vertex w is not labeled as discovered then
5 recursively call DFS(G,w)
A non-recursive implementation of DFS:[6]
1 procedure DFS-iterative(G,v):
2 let S be a stack
3 S.push(v)
4 while S is not empty
5 v = S.pop()
6 if v is not labeled as discovered:
7 label v as discovered
8 for all edges from v to w in G.adjacentEdges(v) do
9 S.push(w)
"""
def DFS(G,v0):
S = []
S.append(v0)
label = set()

while S:
v = S.pop()
if v not in label:
label.add(v)
procedure(v)
for w in G[v]:
S.append(w)
/<code>


分享到:


相關文章: