图:BFS

def bfs(graph, node):
    queue = [node]  # 用数组来表示队列,因为数组和apped和pop取出

    visited = set()  # 用set集合来存储走过的结点,因为set中元素不重复
    visited.add(node)

    '''
        首先node入队列
        取出node结点,将node结点的相邻结点入queue
        依次取出第二层的结点,取出相邻结点入queue
    '''
    while len(queue):
        # 取出首节点,用于读邻结点
        current_node = queue.pop(0)
        if current_node in graph.keys():
            neighbor_nodes = graph[current_node]

            # 将邻结点存入队列
            for i in neighbor_nodes:
                if i not in visited:
                    queue.append(i)
                    visited.add(i)  # 没有走过的邻结点,标记并存入队列
        print(current_node)  # 输出顺序


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

bfs(graph, "A")

猜你喜欢

转载自blog.csdn.net/zmj1582188592/article/details/121765263