实现说明
全部逻辑都在函数 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);
}