1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (C) 2024 Ethan Uppal. All rights reserved.
use std::{
    collections::{HashMap, HashSet},
    hash::Hash
};

pub struct Digraph<Node: Hash + Eq, Edge> {
    adj: HashMap<Node, Vec<(Edge, Node)>>
}

impl<Node: Hash + Eq, Edge> Digraph<Node, Edge> {
    pub fn new() -> Self {
        Self {
            adj: HashMap::new()
        }
    }

    pub fn add_node(&mut self, node: Node) {
        self.adj.insert(node, vec![]);
    }

    pub fn add_edge(&mut self, u: Node, e: Edge, v: Node) {
        if let Some(out) = self.adj.get_mut(&u) {
            out.push((e, v));
        }
    }

    pub fn out_of(&self, node: Node) -> Option<&Vec<(Edge, Node)>> {
        self.adj.get(&node)
    }

    pub fn nodes(&self) -> Vec<&Node> {
        self.adj.keys().collect()
    }

    pub fn node_count(&self) -> usize {
        self.adj.len()
    }
}

impl<Node: Hash + Eq + Clone, Edge> Digraph<Node, Edge> {
    /// Conducts a depth-first search (DFS) starting from `start`, calling `f`
    /// on each node encountered in DFS order. This function performs multiple
    /// `clone()`s of the nodes, which is still performant when nodes are
    /// smart pointers such as `Rc`.
    ///
    /// Requires: `start` is in the graph.
    pub fn dfs<F>(&self, mut f: F, start: Node)
    where
        F: FnMut(Node) {
        assert!(self.adj.contains_key(&start));

        let mut visited = HashSet::new();
        let mut stack = vec![];

        stack.push(start);
        while !stack.is_empty() {
            let node = stack.pop().unwrap();
            visited.insert(node.clone());
            f(node.clone());
            for (_, next) in self.out_of(node).unwrap() {
                stack.push(next.clone());
            }
        }
    }
}