← 中文资源

简体中文版本

DFS 三色标记拓扑排序

DFS 三色标记做拓扑排序:白色未访问、灰色在递归栈中、黑色已完成;每个节点在依赖全部完成后才写入序列,再次遇到灰色节点即报环。

阅读英文原文

实现说明

全部逻辑都在函数 visit、main中。 这个示例中仅有的重复出现在 for &dep in &graph[node] 里。match 表达式是穷尽的——编译器强制没有遗漏的分支。

使用要点

  • 跑完文件,输出里会留下标记——build order:。
  • 运行整个文件:main 会依次驱动 visit。

常见问题

运行「DFS 三色标记拓扑排序」会打印什么?

整个文件跑完,输出行以 build order: 这类前缀开头。

入口签名:fn visit( node: &str, graph: &HashMap<&str, Vec<&str>>, state: &mut HashMap<&str, u8>, order: &mut Vec<&str…

核心语句

Some(1) => return false, // gray seen again: a cycle exists
_ => {}

代码示例

use std::collections::HashMap;

// three-color marking: 0=white (unvisited) 1=gray (on the recursion stack) 2=black (finished)
fn visit(
    node: &str,
    graph: &HashMap<&str, Vec<&str>>,
    state: &mut HashMap<&str, u8>,
    order: &mut Vec<&str>,
) -> bool {
    match state.get(node) {
        Some(2) => return true,
        Some(1) => return false, // gray seen again: a cycle exists
        _ => {}
    }
    state.insert(node, 1);
    for &dep in &graph[node] {
        if !visit(dep, graph, state, order) {
            return false;
        }
    }
    state.insert(node, 2);
    order.push(node);
    true
}

fn main() {
    let graph: HashMap<&str, Vec<&str>> = HashMap::from([
        ("app", vec!["db", "cache"]),
        ("db", vec!["storage"]),
        ("cache", vec!["storage"]),
        ("storage", vec![]),
    ]);

    let mut state: HashMap<&str, u8> = HashMap::new();
    let mut order: Vec<&str> = Vec::new();
    assert!(visit("app", &graph, &mut state, &mut order));
    println!("build order: {:?}", order);
}