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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use crate::graph::Graph;

/// Returns whether the graph contains a cycle by running a node
/// coloring Depth-First-Search (DFS)
pub fn cycle_check<T>(graph: &(impl Graph<T> + 'static)) -> bool {
    #[derive(Clone, PartialEq)]
    enum Colors {
        White,
        Grey,
        Black,
    }

    let mut node_colors = vec![Colors::White; graph.number_of_nodes()];
    let mut stack = Vec::new();

    for root in graph.node_range() {
        if node_colors[root as usize] != Colors::White {
            continue;
        }

        stack.push(root);
        while let Some(&node) = stack.last() {
            // pre-order traversal
            if node_colors[node as usize] != Colors::Grey {
                node_colors[node as usize] = Colors::Grey;

                for edge in graph.edge_range(node) {
                    // push unvisited children to stack
                    let target = graph.target(edge);
                    match node_colors[target as usize] {
                        Colors::White => {
                            stack.push(target);
                        }
                        Colors::Grey => {
                            return true;
                        }
                        _ => {}
                    };
                }
            } else if node_colors[node as usize] == Colors::Grey {
                // post-order traversal
                stack.pop();
                node_colors[node as usize] = Colors::Black;
            }
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use crate::edge::InputEdge;
    use crate::{cycle_check::cycle_check, static_graph::StaticGraph};

    #[test]
    fn no_cycle() {
        type Graph = StaticGraph<i32>;
        let edges = vec![
            InputEdge::new(0, 1, 3),
            InputEdge::new(1, 2, 3),
            InputEdge::new(4, 2, 1),
            InputEdge::new(2, 3, 6),
            InputEdge::new(0, 4, 2),
            InputEdge::new(4, 5, 2),
            InputEdge::new(5, 3, 7),
            InputEdge::new(1, 5, 2),
        ];
        let graph = Graph::new(edges);
        assert!(!cycle_check(&graph));
    }

    #[test]
    fn cycle() {
        type Graph = StaticGraph<i32>;
        let edges = vec![
            InputEdge::new(0, 1, 3),
            InputEdge::new(2, 3, 3),
            InputEdge::new(3, 4, 1),
            InputEdge::new(4, 5, 6),
            InputEdge::new(5, 2, 2),
        ];
        let graph = Graph::new(edges);
        assert!(cycle_check(&graph));
    }
}