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!!! (-)

视频:
https://www.bilibili.com/video/av25761720/?spm_id_from=333.788.videocard.1
https://www.bilibili.com/video/av25763384/?spm_id_from=333.788.videocard.0

你可能感兴趣的:(算法,数据结构)