rust_dsa/
toposort.rs

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
190
191
192
193
use std::collections::{HashMap, HashSet};
use std::hash::Hash;

use crate::DiGraph;

/// Returns a [topological sort](http://en.wikipedia.org/wiki/Topological_sorting)
/// of the graph, if one exists.
///
/// If the graph contains one or more directed cycles, `None` is returned.
///
/// # Example
/// ```
/// use rust_dsa::{DiGraph, topological_sort};
///
/// //    +---+      +---+      +---+
/// //    |'a'| ---> |'b'| ---> |'c'|
/// //    +---+      +---+      +---+
/// let no_cycle = DiGraph::from([('a', 'b', ()), ('b', 'c', ())]);
///
/// assert_eq!(
///     topological_sort(&no_cycle),
///     Some(vec![&'a', &'b', &'c'])
/// );
///
///
/// //    +---+      +---+
/// //    | 1 | ---> | 2 |
/// //    +---+      +---+
/// //      ^          |
/// //      |          v
/// //      |        +---+      +---+
/// //      +------- | 3 | ---> | 4 |
/// //               +---+      +---+
/// let with_cycle = DiGraph::from([
///     (1, 2, ()),
///     (2, 3, ()),
///     (3, 4, ()),
///     (3, 1, ()),
/// ]);
///
/// // `with_cycle` contains a cycle so `topological_sort` returns `None`.
/// assert_eq!(
///     topological_sort(&with_cycle),
///     None
/// );
///
/// use rust_dsa::is_topological_sort;
///
/// let big_graph = DiGraph::from([
///     (1, 2, ()),
///     (2, 3, ()),
///     (4, 3, ()),
///     (3, 5, ()),
///     (5, 6, ()),
///     (6, 7, ()),
///     (7, 8, ()),
///     (5, 9, ()),
///     (9, 10, ()),
///     (5, 10, ()),
///     (10, 11, ()),
///     (10, 8, ()),
///     (5, 12, ()),
///     (12, 13, ()),
///     (12, 14, ()),
///     (12, 8, ()),
///     (8, 15, ()),
/// ]);
///
/// // `big_graph` is acyclic.
/// let sort = topological_sort(&big_graph).unwrap();
///
/// assert!(is_topological_sort(&big_graph, &sort));
/// ```
///
/// # Runtime complexity
/// This function implements [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm),
/// so it runs in *O*(*N* + *E*) time where *N* is the number of nodes and *E* is the number of edges.
pub fn topological_sort<N, E>(graph: &DiGraph<N, E>) -> Option<Vec<&N>>
where
    N: Hash + Eq,
{
    let mut sorted = Vec::new();
    let mut neighbor_map = get_neighbor_map(graph);
    let mut indegrees = get_indegrees(&neighbor_map);
    let mut indegree_zero: Vec<_> = indegrees
        .iter()
        .filter(|(_, &count)| count == 0)
        .map(|(node, _)| *node)
        .collect();

    while let Some(node) = indegree_zero.pop() {
        sorted.push(node);
        for neighbor in neighbor_map[node].clone() {
            neighbor_map.get_mut(node).unwrap().remove(neighbor);
            *indegrees.get_mut(neighbor).unwrap() -= 1;
            if indegrees[neighbor] == 0 {
                indegree_zero.push(neighbor);
            }
        }
    }

    if indegrees.into_values().all(|indegree| indegree == 0) {
        Some(sorted)
    } else {
        None
    }
}

fn get_neighbor_map<N, E>(graph: &DiGraph<N, E>) -> HashMap<&N, HashSet<&N>>
where
    N: Hash + Eq,
{
    graph
        .into_iter()
        .map(|node| (node, graph.neighbors_of(node).map(|(n, _)| n).collect()))
        .collect()
}

fn get_indegrees<'a, N>(neighbor_map: &HashMap<&'a N, HashSet<&'a N>>) -> HashMap<&'a N, usize>
where
    N: Hash + Eq,
{
    let mut indegrees: HashMap<_, _> = neighbor_map
        .keys()
        .cloned()
        .zip(std::iter::repeat(0))
        .collect();

    for neighbors in neighbor_map.values() {
        for neighbor in neighbors {
            *indegrees.get_mut(neighbor).unwrap() += 1;
        }
    }

    indegrees
}

/// Returns `true` if the ordering is a topological sort for the graph.
///
/// Returns `false` if the ordering is *not* a topological sort or if the graph contains cycles.
///
/// # Example
/// ```
/// use rust_dsa::{DiGraph, is_topological_sort};
///
/// //    +---+      +---+      +---+
/// //    |'a'| ---> |'b'| ---> |'c'|
/// //    +---+      +---+      +---+
/// let graph = DiGraph::from([('a', 'b', ()), ('b', 'c', ())]);
///
/// assert!(is_topological_sort(
///     &graph,
///     &[&'a', &'b', &'c']
/// ));
///
/// assert!(!is_topological_sort(
///     &graph,
///     &[&'b', &'a', &'c']
/// ));
///
/// assert!(!is_topological_sort(
///     &graph,
///     &[&'a', &'b']
/// ));
/// ```
pub fn is_topological_sort<N, E>(graph: &DiGraph<N, E>, sort: &[&N]) -> bool
where
    N: Hash + Eq,
{
    if sort.len() > graph.len() {
        return false;
    }

    let sort_inv: HashMap<_, _> = sort
        .iter()
        .enumerate()
        .map(|(i, node)| (*node, i))
        .collect();

    for node in graph.iter() {
        if !sort_inv.contains_key(node) {
            return false;
        }
    }

    for (from, to, _) in graph.edges() {
        if sort_inv[from] > sort_inv[to] {
            return false;
        }
    }

    true
}