最近複習題目,發現對圖的python實現比較無知,所以實現一下。
在python中採用字典來表示圖的結構,訪問非常方便。
BFS與DFS非遞歸的寫法最大的差別是在遍歷的過程中路過的結點一個用隊列保存,一個用棧保存,其他結構幾乎是一樣的!
這麼理解的話應該很好記憶了
直接上代碼
graph={ 1:[2,6], 2:[1,3], 3:[2,4,6], 4:[3,5], 5:[4,6], 6:[1,3,5] } def DFS(graph,s): stack = [] # 所有結點入隊 stack.append(s) # 記錄看過的結點 seen = set() seen.add(s) while (len(stack) > 0): # 每次拿一個結點出來 vertex = stack.pop() # 結點的鄰接點 nodes = graph[vertex] for w in nodes: if w not in seen: # 如果w沒挖掘過,就放進去 stack.append(w) seen.add(w) print(vertex) return def BFS(graph,s): #用空的數組做一個隊列 queue=[] #所有結點入隊 queue.append(s) #記錄看過的結點 seen = set() seen.add(s) while(len(queue)>0): #每次拿一個結點出來 vertex = queue.pop(0) #結點的鄰接點 nodes=graph[vertex] for w in nodes: if w not in seen: #如果w沒挖掘過,就放進去 queue.append(w) seen.add(w) print(vertex) return BFS(graph,list(graph.keys())[0]) DFS(graph,list(graph.keys())[0])