← 中文资源

简体中文版本

无权图 BFS 最短路径(Python)

用广度优先搜索在无权图中找最短路径并重建路径。

阅读英文原文

实现说明

逻辑集中在函数 bfs_shortest_path里。 驱动整个流程的是 while queue 这一个循环。 为结果新分配了一个值;入参原样保留。

使用要点

  • 把 bfs_shortest_path 当作 API:导入它,其余代码可以忽略。

常见问题

bfs_shortest_path 会修改传入的参数吗?

不会。代码构造并返回新值,入参保持原样,对共享或冻结的数据结构调用是安全的。

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 bfs_shortest_path。

入口签名:def bfs_shortest_path(graph, start, end)

核心语句

return [start]
queue = deque([start])
visited = {start}

代码示例

from collections import deque


def bfs_shortest_path(graph, start, end):
    if start == end:
        return [start]
    queue = deque([start])
    visited = {start}
    parent = {}
    while queue:
        node = queue.popleft()
        for neighbor in graph.get(node, []):
            if neighbor in visited:
                continue
            visited.add(neighbor)
            parent[neighbor] = node
            if neighbor == end:
                path = [end]
                cur = end
                while cur in parent:
                    cur = parent[cur]
                    path.insert(0, cur)
                return path
            queue.append(neighbor)
    return None