蓝色天空.知识 · 实践 · 创造
我的收藏
数据结构与算法 教程目录 44章
数据结构与算法 / LEARN BY DOING

寻路算法

详解基于深度优先遍历(DFS)与前驱数组 from[] 的单源图寻路算法,包括可达性判断 hasPath(w) 与借助栈逆向回溯还原正向路径 path(w) 的完整实现。

学完这一章,你能够

  • 详解基于深度优先遍历(DFS)与前驱数组 from[] 的单源图寻路算法,包括可达性判断 hasPath(w) 与借助栈逆向回溯还原正向路径 path(w) 的完整实现。

前驱数组 from[] 与单源 DFS 寻路初始化

深度优先遍历不仅能判断连通性,还能进一步求解从指定源点 `s` 到图中任意可达顶点 `w` 的具体路径。为此在 DFS 框架中新增前驱数组 `from[]`,其中 `from[i]` 记录本次搜索路径上顶点 `i` 是从哪一个相邻顶点走过来的。构造函数先分配 `visited = new boolean[G.V()]` 与 `from = new int[G.V()]`(注:原参考文段落此处误重复写作两个 `from = new int[G.V()]`),将 `visited` 全部置为 `false`、`from` 全部置为 `-1`,然后仅从起点 `s` 启动一次 `dfs(s)`;递归深入未访问邻接点 `i` 前记录 `from[i] = v`。

可达性判断 hasPath 与栈逆向回溯路径

由于 `dfs(s)` 只会访问与起点 `s` 连通的顶点,查询 `s` 到 `w` 是否存在路径的 `hasPath(w)` 只需 O(1) 返回 `visited[w]`。若要还原 `s` 到 `w` 的具体路径,先通过 `hasPath(w)` 确认可达,再令游标 `p = w` 沿 `from[p]` 不断倒推直至遇到起点前驱哨兵 `-1`,将途经节点依次压入辅助栈;最后不断弹出栈顶元素写入结果列表,即可将逆序回溯翻转成从 `s` 到 `w` 的正向路径。

在完整类 `Path` 中,`showPath(w)` 调用 `path(w)` 并以 `->` 连接打印整条路径;需要注意 DFS 找到的是一条可行简单路径,并不保证边数最少。本站离线 Python 实验脚本完整验证了源点前驱为 `-1`、不可达顶点返回 `False` 并受断言保护、路径每段均为有效图边以及起点到自身返回 `[s]`。

离线校验 DFS 单源寻路的 from[] 前驱记录、hasPath 与栈逆向路径还原

含完整源码 · 169 行
展开查看收起
python
"""Offline algorithm verification lab for Chapter 43 (graph-theory-path)."""
import json

VERSION = "CPython 3.12.14 offline DSA verifier (graph-theory-path)"


class SparseGraph:
    def __init__(self, n: int):
        self.n = n
        self.g = [[] for _ in range(n)]

    def V(self) -> int:
        return self.n

    def add_edge(self, v: int, w: int) -> None:
        self.g[v].append(w)
        if v != w:
            self.g[w].append(v)

    def has_edge(self, v: int, w: int) -> bool:
        return w in self.g[v]

    def adj(self, v: int):
        return self.g[v]


class DFSPath:
    """Single-source path finding via DFS and predecessor array from[]."""

    def __init__(self, graph: SparseGraph, s: int):
        assert 0 <= s < graph.V()
        self.G = graph
        self.s = s
        self.visited = [False] * graph.V()
        self.frm = [-1] * graph.V()
        self._dfs(s)

    def _dfs(self, v: int) -> None:
        self.visited[v] = True
        for i in self.G.adj(v):
            if not self.visited[i]:
                self.frm[i] = v
                self._dfs(i)

    def has_path(self, w: int) -> bool:
        assert 0 <= w < self.G.V()
        return self.visited[w]

    def path(self, w: int) -> list:
        assert self.has_path(w), f"No path from {self.s} to {w}"
        stack = []
        p = w
        while p != -1:
            stack.append(p)
            p = self.frm[p]
        res = []
        while stack:
            res.append(stack.pop())
        return res

    def format_path(self, w: int) -> str:
        return " -> ".join(str(x) for x in self.path(w))


def _build_sample_graph() -> SparseGraph:
    # Component 1: 0..6; Component 2: 7..8
    g = SparseGraph(9)
    for u, v in [(0, 1), (0, 2), (0, 5), (0, 6), (5, 3), (5, 4), (3, 4), (4, 6), (7, 8)]:
        g.add_edge(u, v)
    return g


def case_dfs_path_init_and_has_path():
    g = _build_sample_graph()
    finder = DFSPath(g, 0)
    expected = {
        "source_from_is_minus_one": True,
        "has_path_6": True,
        "has_path_3": True,
        "has_path_7": False,
        "has_path_8": False,
        "unreached_from_7_is_minus_one": True,
    }
    actual = {
        "source_from_is_minus_one": finder.frm[0] == -1,
        "has_path_6": finder.has_path(6),
        "has_path_3": finder.has_path(3),
        "has_path_7": finder.has_path(7),
        "has_path_8": finder.has_path(8),
        "unreached_from_7_is_minus_one": finder.frm[7] == -1,
    }
    return {
        "name": "dfs_path_init_and_has_path",
        "summary": "验证 DFSPath 构造函数初始化 visited 与 from 数组,并以 O(1) hasPath(w) 区分可达与不可达顶点",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_dfs_path_backtrack_with_stack():
    g = _build_sample_graph()
    finder = DFSPath(g, 0)
    p6 = finder.path(6)
    p4 = finder.path(4)
    all_edges_valid_6 = all(g.has_edge(p6[i], p6[i + 1]) for i in range(len(p6) - 1))
    all_edges_valid_4 = all(g.has_edge(p4[i], p4[i + 1]) for i in range(len(p4) - 1))
    expected = {
        "path_to_6": [0, 5, 3, 4, 6],
        "path_to_4": [0, 5, 3, 4],
        "edges_valid": True,
        "starts_at_0_ends_at_6": True,
    }
    actual = {
        "path_to_6": p6,
        "path_to_4": p4,
        "edges_valid": all_edges_valid_6 and all_edges_valid_4,
        "starts_at_0_ends_at_6": p6[0] == 0 and p6[-1] == 6,
    }
    return {
        "name": "dfs_path_backtrack_with_stack",
        "summary": "验证沿 from 数组逆向入栈再出栈还原正向路径,且路径相邻节点均为图中有效边",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_dfs_path_full_class_and_self_path():
    g = _build_sample_graph()
    finder = DFSPath(g, 0)
    unreachable_guarded = False
    try:
        finder.path(7)
    except AssertionError:
        unreachable_guarded = True
    expected = {
        "self_path": [0],
        "formatted_path_6": "0 -> 5 -> 3 -> 4 -> 6",
        "formatted_self": "0",
        "unreachable_guarded": True,
    }
    actual = {
        "self_path": finder.path(0),
        "formatted_path_6": finder.format_path(6),
        "formatted_self": finder.format_path(0),
        "unreachable_guarded": unreachable_guarded,
    }
    return {
        "name": "dfs_path_full_class_and_self_path",
        "summary": "验证起点到自身的路径 [0]、箭头格式输出及不可达目标调用 path() 的断言防护",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_dfs_path_init_and_has_path(),
        case_dfs_path_backtrack_with_stack(),
        case_dfs_path_full_class_and_self_path(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
在 CPython 3.12.14 离线脚本中确认 from[0]==-1、hasPath 准确区分连通分量、path(6) 经栈回溯还原为有效路径 [0,5,3,4,6] 且不可达点受断言保护。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2641.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip

下载课程关联工程包:数据结构与算法

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2664.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为 `dfs(s)` 只会在 `if (!visited[i])` 成立时设置 `from[i] = v`,每个被访问的非起点节点都恰好被记录一个更早发现的前驱,形成一棵以 `s` 为根、无环的 DFS 生成树,且源点 `s` 的 `from[s]` 始终保持初始哨兵 `-1`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习