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
//! Separate components of an undirected graph into disjoint sets.
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::iter::once;
fn join(table: &mut [usize], mut rx: usize, mut ry: usize) -> usize {
while table[rx] != table[ry] {
if table[rx] > table[ry] {
if rx == table[rx] {
table[rx] = table[ry];
break;
}
let z = table[rx];
table[rx] = table[ry];
rx = z;
} else {
if ry == table[ry] {
table[ry] = table[rx];
break;
}
let z = table[ry];
table[ry] = table[rx];
ry = z;
}
}
table[rx]
}
fn find(table: &mut [usize], mut x: usize) -> usize {
while table[x] != x {
let t = table[x];
table[x] = table[table[x]];
x = t;
}
x
}
/// Separate components of an undirected graph into disjoint sets.
///
/// - `groups` is a set of group of vertices connected together. It is
/// acceptable for a group to contain only one node. Empty groups
/// receive special treatment (see below).
///
/// This function returns a pair containing:
///
/// - A mapping from every vertex to its set identifier. The set identifiers are
/// opaque and will not necessarily be compact. However, it is guaranteed that
/// they will not be greater than the number of groups.
/// - A mapping from every group to its set identifier, with the identifiers being
/// the same ones as the ones in the previous mapping. Each group corresponds to
/// the identifier at the same index, except for empty group whose identifier is
/// set to `std::usize::MAX`.
///
/// Note that if you have a raw undirected graph, you can build
/// such a structure by creating a group for every vertex containing
/// the vertex itself and its immediate neighbours.
#[must_use]
pub fn separate_components<N>(groups: &[Vec<N>]) -> (HashMap<&N, usize>, Vec<usize>)
where
N: Hash + Eq,
{
let mut table = (0..groups.len()).collect::<Vec<_>>();
let mut indices = HashMap::new();
for (mut group_index, group) in groups.iter().enumerate() {
if group.is_empty() {
table[group_index] = usize::MAX;
}
for element in group {
match indices.entry(element) {
Occupied(e) => {
group_index = join(&mut table, group_index, *e.get());
}
Vacant(e) => {
e.insert(group_index);
}
}
}
}
for group_index in indices.values_mut() {
*group_index = find(&mut table, *group_index);
}
// Flatten the table.
for group_index in 0..groups.len() {
if table[group_index] != usize::MAX {
let target = find(&mut table, group_index);
table[group_index] = target;
}
}
(indices, table)
}
/// Separate components of an undirected graph into disjoint sets.
///
/// - `groups` is a set of group of vertices connected together. It is
/// acceptable for a group to contain only one node.
///
/// This function returns a list of sets of nodes forming disjoint connected
/// sets.
#[must_use]
pub fn components<N>(groups: &[Vec<N>]) -> Vec<HashSet<N>>
where
N: Clone + Hash + Eq,
{
let (_, gindices) = separate_components(groups);
let mut gb = gindices
.into_iter()
.enumerate()
.filter(|&(_, n)| n != usize::MAX)
.collect::<Vec<_>>();
gb.sort_unstable_by(|&(_, n1), &(_, n2)| Ord::cmp(&n1, &n2));
let mut key = None;
let mut res = vec![];
for (group_index, k) in gb {
if key != Some(k) {
res.push(HashSet::default());
key = Some(k);
}
if let Some(set) = res.last_mut() {
for item in &groups[group_index] {
set.insert(item.clone());
}
}
}
res
}
/// Extract connected components from a graph.
///
/// - `starts` is a collection of vertices to be considered as start points.
/// - `neighbours` is a function returning the neighbours of a given node.
///
/// This function returns a list of sets of nodes forming disjoint connected
/// sets.
pub fn connected_components<N, FN, IN>(starts: &[N], mut neighbours: FN) -> Vec<HashSet<N>>
where
N: Clone + Hash + Eq,
FN: FnMut(&N) -> IN,
IN: IntoIterator<Item = N>,
{
components(
&starts
.iter()
.map(|s| neighbours(s).into_iter().chain(once(s.clone())).collect())
.collect::<Vec<_>>(),
)
}
/// Locate vertices amongst disjoint sets.
///
/// - `components` are disjoint vertices sets.
///
/// This function returns a map between every vertex and the index of
/// the set it belongs to in the `components` list.
#[allow(clippy::implicit_hasher)]
#[must_use]
pub fn component_index<N>(components: &[HashSet<N>]) -> HashMap<N, usize>
where
N: Clone + Hash + Eq,
{
let mut assoc = HashMap::with_capacity(components.len());
for (i, c) in components.iter().enumerate() {
for n in c {
assoc.insert(n.clone(), i);
}
}
assoc
}