欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python BFS广度优先搜索与DFS深度优先搜索

程序员文章站 2022-05-23 11:28:34
...

无向图

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, s):
    queue = []
    queue.append(s)
    seen = set()  # seen数组看是否访问过此节点
    seen.add(s)
    while len(queue) > 0:
        vertex = queue.pop(0)
        nodes = graph[vertex]  # graph['A']=['B', 'C']
        for w in nodes:
            if w not in seen:
                queue.append(w)
                seen.add(w)
        print(vertex, end=' ')


BFS(graph, 'A')

输出

A B C D E F 

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 BFS(graph, s):
    stack = []
    stack.append(s)
    seen = set()  # seen数组看是否访问过此节点
    seen.add(s)
    while len(stack) > 0:
        vertex = stack.pop()
        nodes = graph[vertex]  # graph['A']=['B', 'C']
        for w in nodes:
            if w not in seen:
                stack.append(w)
                seen.add(w)
        print(vertex, end=' ')


BFS(graph, 'A')

输出

A C E D F B