蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。explore-graph-theory-path.py
explore-graph-theory-path.py169 行
"""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()
本例需在 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。

入口文件:projects/data-structures-graph-theory-path-lab/explore-graph-theory-path.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-graph-theory-path.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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