BFS和DFS

  • BFS是利用队列来保存将要处理的结点,一层一层地遍历。BFS可以用来计算最短路径
  • DFS是利用堆栈来保存将要处理的结点,一条路走到黑,走不通的时候回溯,然后从堆栈里拿到的结点正好是上一级的邻接点
# -*- coding:utf-8 -*-

def BFS(graph, s):

    # 初始化三个东西:queue, seen, parent
    queue = [s]
    seen = set()
    seen.add(s)
    parent = {s: None}

    while (len(queue) > 0):

        # 队列是pop(0)
        cur = queue.pop(0)
        # 获得cur的相邻结点
        nodes = graph[cur]

        for w in nodes:
            if w not in seen:
                # 三个操作
                queue.append(w)
                seen.add(w)
                parent[w] = cur
    return parent

def DFS(graph, s):

    # 初始化三个东西: stack, seen, parent
    stack = [s]
    seen = set()
    seen.add(s)
    parent = {s: None}

    while (len(stack) > 0):

        # 堆栈是pop()
        cur = stack.pop()
        # 获得cur的相邻结点
        nodes = graph[cur]

        for w in nodes:
            if w not in seen:
                # 三个操作
                stack.append(w)
                seen.add(w)
                parent[w] = cur
    return parent

graph = {
    "A": {"B", "C"},
    "B": {"A", "C", "D"},
    "C": {"A", "B", "D", "E"},
    "D": {"B", "C", "E", "F"},
    "E": {"C", "D"},
    "F": {"D"}
}

res = DFS(graph, "A")
print(res)



你可能感兴趣的:(BFS和DFS)