1. 程式人生 > >Python 實現 BFS 和 DFS

Python 實現 BFS 和 DFS

# BFS
graph = {
    "A" : ["B", "C"],
    "B" : ["A", "C", "D"],
    "C" : ["A", "B", "D", "E"],
    "D" : ["B", "C", "E", "F"],
    "E" : ["C", "D"],
    "F" : ["D"]
}

def BFS(graph, startNode):
    queue = []
    queue.append(startNode)
    seen = set()
    seen.add(startNode)

    while (len(queue)
> 0): vertex = queue.pop(0) print(vertex) nodes = graph[vertex] for w in nodes: if w not in seen: queue.append(w) seen.add(w) BFS(graph, "A")

BFS 使用佇列控制遍歷路徑,隊首彈出當前需要訪問的結點,隊尾插入與當前結點相連的結點。

# DFS
graph = {
    "A" : ["B", "C"
], "B" : ["A", "C", "D"], "C" : ["A", "B", "D", "E"], "D" : ["B", "C", "E", "F"], "E" : ["C", "D"], "F" : ["D"] } def DFS(graph, startNode): stack = [] stack.append(startNode) seen = set() seen.add(startNode) while (len(stack) > 0): vertex = stack.
pop() print(vertex) nodes = graph[vertex] for w in nodes: if w not in seen: stack.append(w) seen.add(w) DFS(graph, "A")

DFS 使用堆疊控制遍歷(訪問)路徑。

仔細觀察可以發現在由 BFS 改寫成 DFS 的過程中,只需要改動一個地方即可,pop(0) 是 BFS,pop()就是 DFS。 甚至都不用將 queue 改成 stack。Amazing!!! (-)