Topological Sort With DFS Coloring

DFS with a three-state color map orders dependencies before dependents and reports false the moment an in-progress node is visited again.

RustData Integrity

Code

rustsnippet
38 lines
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);
}

What the code does

Under the hood: the functions visit and main.

Iteration happens inside for &dep in &graph[node] — everything outside it runs once. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Applying it

Entry signature: fn visit( node: &str, graph: &HashMap<&str, Vec<&str>>, state: &mut HashMap<&str, u8>, order: &mut Vec<&str…

The run emits 1 labeled section — build order: — one per step.

The sequence visit lives in main; running the file triggers it.

Statements that decide the outcome

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

Interactive Tools for This Topic

FAQ

What does Topological Sort With DFS Coloring print when run?
Invoke the file as-is — the `build order:` prefixes identify which step printed each line.