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

离线校验图 DFS 访问顺序、13 顶点 3 连通分量计数与 O(1) 连通查询

PYTHONWindows x64、CPython 3.12.14 离线数据结构与算法验证脚本(标准库实现,无网络依赖)。explore-graph-theory-deep.py
explore-graph-theory-deep.py171 行
"""Offline algorithm verification lab for Chapter 42 (graph-theory-deep)."""
import json

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


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 adj(self, v: int):
        return self.g[v]


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

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

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

    def adj(self, v: int):
        return [i for i in range(self.n) if self.g[v][i]]


class Components:
    """DFS-based connected components counter and O(1) connectivity oracle."""

    def __init__(self, graph):
        self.G = graph
        self.visited = [False] * graph.V()
        self.id = [-1] * graph.V()
        self.ccount = 0
        self.visit_order = []

        for i in range(graph.V()):
            if not self.visited[i]:
                self._dfs(i)
                self.ccount += 1

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

    def count(self) -> int:
        return self.ccount

    def is_connected(self, v: int, w: int) -> bool:
        assert 0 <= v < self.G.V() and 0 <= w < self.G.V()
        return self.id[v] == self.id[w]


def case_dfs_traversal_order():
    g = SparseGraph(7)
    for u, v in [(0, 1), (0, 2), (0, 5), (0, 6), (5, 3), (5, 4), (3, 4), (4, 6)]:
        g.add_edge(u, v)
    comp = Components(g)
    expected = {
        "visit_order": [0, 1, 2, 5, 3, 4, 6],
        "visited_all": True,
        "component_count": 1,
    }
    actual = {
        "visit_order": comp.visit_order,
        "visited_all": all(comp.visited),
        "component_count": comp.count(),
    }
    return {
        "name": "dfs_traversal_order",
        "summary": "验证从顶点 0 出发的递归深度优先遍历顺序 [0,1,2,5,3,4,6] 与环路不重复访问保证",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_connected_components_count_and_id():
    # Classic 13-vertex graph with 3 connected components: {0..6}, {7,8}, {9..12}
    g = SparseGraph(13)
    edges = [
        (0, 5), (4, 3), (0, 1), (9, 12), (6, 4), (5, 4),
        (0, 2), (11, 12), (9, 10), (0, 6), (7, 8), (9, 11), (5, 3),
    ]
    for u, v in edges:
        g.add_edge(u, v)
    comp = Components(g)
    expected = {
        "ccount": 3,
        "id_array": [0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
        "connected_0_4": True,
        "connected_7_8": True,
        "connected_0_9": False,
        "connected_7_12": False,
    }
    actual = {
        "ccount": comp.count(),
        "id_array": comp.id,
        "connected_0_4": comp.is_connected(0, 4),
        "connected_7_8": comp.is_connected(7, 8),
        "connected_0_9": comp.is_connected(0, 9),
        "connected_7_12": comp.is_connected(7, 12),
    }
    return {
        "name": "connected_components_count_and_id",
        "summary": "在 13 顶点非连通无向图上用 DFS 求出 3 个连通分量,并校验 id 数组标记与 O(1) isConnected 查询",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_dfs_components_dense_vs_sparse():
    edges = [(0, 1), (1, 2), (4, 5)]  # 7 vertices -> {0,1,2}, {3}, {4,5}, {6} => 4 components
    sg = SparseGraph(7)
    dg = DenseGraph(7)
    for u, v in edges:
        sg.add_edge(u, v)
        dg.add_edge(u, v)
    c_sparse = Components(sg)
    c_dense = Components(dg)
    expected = {
        "sparse_count": 4,
        "dense_count": 4,
        "id_arrays_identical": True,
        "isolated_3_not_connected_to_6": True,
    }
    actual = {
        "sparse_count": c_sparse.count(),
        "dense_count": c_dense.count(),
        "id_arrays_identical": c_sparse.id == c_dense.id,
        "isolated_3_not_connected_to_6": not c_sparse.is_connected(3, 6),
    }
    return {
        "name": "dfs_components_dense_vs_sparse",
        "summary": "在含孤立顶点的 7 节点图上验证邻接表与邻接矩阵运行 Components 得到完全相同的连通分量划分",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_dfs_traversal_order(),
        case_connected_components_count_and_id(),
        case_dfs_components_dense_vs_sparse(),
    ]
    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-deep-lab/explore-graph-theory-deep.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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