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
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
//! Implementation of finding an Eulerian Path on a graph. This implementation verifies that the
//! input graph is fully connected and supports self loops and repeated edges between nodes.
//!
//! Time Complexity: $O(E)$
//!
//! # Resources
//!
//! - [W. Fiset's video 1](https://www.youtube.com/watch?v=xR4sGgwtR2I&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=27)
//! - [W. Fiset's video 2](https://www.youtube.com/watch?v=8MpoO2zA2l4&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=28)

use crate::algo::graph::UnweightedAdjacencyList;

#[derive(Debug)]
pub enum EulerianPathError {
    DisconnectedGraph,
    InvalidDegrees,
}

impl UnweightedAdjacencyList {
    fn count_in_out_degrees(&self) -> [Vec<usize>; 2] {
        let mut in_degrees = vec![0; self.node_count()];
        let mut out_degrees = vec![0; self.node_count()];
        for [from, to] in self.edges() {
            out_degrees[from] += 1;
            in_degrees[to] += 1;
        }
        [in_degrees, out_degrees]
    }
    /// Returns a list of `edge_count + 1` node ids that give the Eulerian path or
    /// an `EulerianPathError` if no path exists or the graph is disconnected.
    pub fn eulerian_path(&self) -> Result<Vec<usize>, EulerianPathError> {
        let n = self.node_count();
        let has_eulerian_path = |[in_degrees, out_degrees]: [&[usize]; 2]| {
            let mut start = None;
            let mut has_end = false;
            let mut start_default = None;
            for (node, (&i, &o)) in in_degrees.iter().zip(out_degrees.iter()).enumerate() {
                if (i as isize - o as isize).abs() > 1 {
                    return None;
                }
                if i.wrapping_sub(o) == 1 {
                    if has_end {
                        return None;
                    } else {
                        has_end = true;
                    }
                }
                if o.wrapping_sub(i) == 1 {
                    if start.is_some() {
                        return None;
                    } else {
                        start = Some(node)
                    }
                }
                if start_default.is_none() && o > 0 {
                    start_default = Some(node);
                }
            }
            if start.is_some() ^ has_end {
                None
            } else {
                Some(start.unwrap_or_else(|| start_default.unwrap()))
            }
        };
        let [i, mut o] = self.count_in_out_degrees();
        fn _dfs(
            g: &UnweightedAdjacencyList,
            out: &mut Vec<usize>,
            path: &mut Vec<usize>,
            at: usize,
        ) {
            // while the current node still has outgoing edge(s)
            while out[at] > 0 {
                out[at] -= 1;
                // select the next unvisited outgoing edge
                let next = g[at][out[at]];
                _dfs(g, out, path, next);
            }
            // add current node to solution.
            path.push(at);
        };
        has_eulerian_path([&i, &o]).map_or(Err(EulerianPathError::InvalidDegrees), |start| {
            let mut path = Vec::with_capacity(n);
            _dfs(self, &mut o, &mut path, start);
            path.reverse();
            // Make sure all edges of the graph were traversed. It could be the
            // case that the graph is disconnected.
            if path.len() == self.edge_count() + 1 {
                Ok(path)
            } else {
                // disconnected graph
                Err(EulerianPathError::DisconnectedGraph)
            }
        })
    }
}
#[cfg(test)]
mod tests {

    use super::*;
    #[test]
    fn test_eulerian_path() {
        let g = UnweightedAdjacencyList::new_directed(
            7,
            &[
                [1, 2],
                [1, 3],
                [2, 2],
                [2, 4],
                [2, 4],
                [3, 1],
                [3, 2],
                [3, 5],
                [4, 3],
                [4, 6],
                [5, 6],
                [6, 3],
            ],
        );
        let path = g.eulerian_path().unwrap();
        assert_eq!(&path, &[1, 3, 5, 6, 3, 2, 4, 3, 1, 2, 2, 4, 6]);

        let g = UnweightedAdjacencyList::new_directed(
            5,
            &[[0, 1], [1, 2], [1, 4], [1, 3], [2, 1], [4, 1]],
        );
        let path = g.eulerian_path().unwrap();
        assert_eq!(&path, &[0, 1, 4, 1, 2, 1, 3]);
    }
    #[test]
    fn test_eulerian_path_invalid1() {
        let g = UnweightedAdjacencyList::new_directed(2, &[[0, 1], [0, 1]]);
        assert!(matches!(
            g.eulerian_path(),
            Err(EulerianPathError::InvalidDegrees)
        ));
    }
    #[test]
    fn test_eulerian_path_invalid2() {
        let g = UnweightedAdjacencyList::new_directed(3, &[[0, 1], [1, 0], [1, 2], [2, 0], [2, 0]]);
        assert!(matches!(
            g.eulerian_path(),
            Err(EulerianPathError::InvalidDegrees)
        ));
    }
    #[test]
    fn test_eulerian_path_invalid3() {
        let g = UnweightedAdjacencyList::new_directed(
            4,
            &[
                [0, 2],
                [2, 1],
                [2, 3],
                [3, 0],
                [3, 1],
                [1, 3],
                [1, 0],
                [1, 2],
                [0, 3],
                [2, 0],
            ],
        );
        assert!(matches!(
            g.eulerian_path(),
            Err(EulerianPathError::InvalidDegrees)
        ));
    }

    #[test]
    fn test_eulerian_path_invalid4() {
        let g = UnweightedAdjacencyList::new_directed(
            8,
            &[
                [0, 1],
                [1, 2],
                [2, 3],
                [3, 1],
                [4, 5],
                [5, 6],
                [6, 7],
                [7, 4],
            ],
        );
        assert!(matches!(
            g.eulerian_path(),
            Err(EulerianPathError::DisconnectedGraph)
        ));
    }
}