|
| 1 | +use std::collections::{BTreeMap, VecDeque}; |
| 2 | + |
| 3 | +type Graph<V, E> = BTreeMap<V, Vec<(V, E)>>; |
| 4 | + |
| 5 | +/// returns topological sort of the graph using Kahn's algorithm |
| 6 | +pub fn topological_sort<V: Ord + Copy, E: Ord>(graph: &Graph<V, E>) -> Vec<V> { |
| 7 | + let mut visited = BTreeMap::new(); |
| 8 | + let mut degree = BTreeMap::new(); |
| 9 | + for u in graph.keys() { |
| 10 | + degree.insert(*u, 0); |
| 11 | + for (v, _) in graph.get(u).unwrap() { |
| 12 | + let entry = degree.entry(*v).or_insert(0); |
| 13 | + *entry += 1; |
| 14 | + } |
| 15 | + } |
| 16 | + let mut queue = VecDeque::new(); |
| 17 | + for (u, d) in degree.iter() { |
| 18 | + if *d == 0 { |
| 19 | + queue.push_back(*u); |
| 20 | + visited.insert(*u, true); |
| 21 | + } |
| 22 | + } |
| 23 | + let mut ret = Vec::new(); |
| 24 | + while let Some(u) = queue.pop_front() { |
| 25 | + ret.push(u); |
| 26 | + if let Some(from_u) = graph.get(&u) { |
| 27 | + for (v, _) in from_u { |
| 28 | + *degree.get_mut(v).unwrap() -= 1; |
| 29 | + if *degree.get(v).unwrap() == 0 { |
| 30 | + queue.push_back(*v); |
| 31 | + visited.insert(*v, true); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + ret |
| 37 | +} |
| 38 | + |
| 39 | +#[cfg(test)] |
| 40 | +mod tests { |
| 41 | + use std::collections::BTreeMap; |
| 42 | + |
| 43 | + use super::{topological_sort, Graph}; |
| 44 | + fn add_edge<V: Ord + Copy, E: Ord>(graph: &mut Graph<V, E>, from: V, to: V, weight: E) { |
| 45 | + let edges = graph.entry(from).or_insert(Vec::new()); |
| 46 | + edges.push((to, weight)); |
| 47 | + } |
| 48 | + |
| 49 | + #[test] |
| 50 | + fn it_works() { |
| 51 | + let mut graph = BTreeMap::new(); |
| 52 | + add_edge(&mut graph, 1, 2, 1); |
| 53 | + add_edge(&mut graph, 1, 3, 1); |
| 54 | + add_edge(&mut graph, 2, 3, 1); |
| 55 | + add_edge(&mut graph, 3, 4, 1); |
| 56 | + add_edge(&mut graph, 4, 5, 1); |
| 57 | + add_edge(&mut graph, 5, 6, 1); |
| 58 | + add_edge(&mut graph, 6, 7, 1); |
| 59 | + |
| 60 | + assert_eq!(topological_sort(&graph), vec![1, 2, 3, 4, 5, 6, 7]); |
| 61 | + } |
| 62 | +} |
0 commit comments