graphity_core/biconnectivity.rs
1use crate::{
2 BiAdjacentGraph, EdgeMapping, EdgePartition, Edges, NONE, SortedIntView, growth, parent_forest,
3};
4
5/// The bridges, articulation points and biconnected components of a graph read as undirected, as
6/// [`components::biconnectivity_of`](crate::components::biconnectivity_of) returns them.
7///
8/// A bridge is an edge whose removal increases the number of connected components, and an articulation
9/// point is a node whose removal does the same. A biconnected component, also called a block, is a
10/// maximal group of edges in which any two edges lie on a common cycle. The blocks partition the
11/// edges, not the nodes: an articulation point belongs to every block it touches.
12///
13/// The graph is read as undirected, as described at [`components`](crate::components): the edges
14/// `a -> b` and `b -> a` are one undirected edge. So a graph that stores its edges in both directions
15/// still has bridges, and the two directions of an edge lie in the same block. Self-loops are in no
16/// block and never a bridge. Here, the control flow of the method `load`, whose loop is connected to
17/// the rest only through `header`:
18///
19/// <!-- example: connectivity.rs#biconnectivity -->
20/// ```
21/// # use graphity_core::{BiAdjacentGraph, components};
22/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
23/// let biconnectivity = components::biconnectivity_of(&BiAdjacentGraph::of(&cfg));
24/// let bridges = biconnectivity.bridges();
25/// // bridges: entry -> header, header -> exit
26/// let articulation_points = biconnectivity.articulation_points();
27/// // articulation_points: [1] - header
28/// # assert_eq!(bridges.source_nodes(), [0, 1]);
29/// # assert_eq!(bridges.target_nodes(), [1, 5]);
30/// # assert_eq!(articulation_points, [1]);
31/// ```
32///
33/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
34///
35/// **Memory:** up to 8 x edge_count + 20 x node_count bytes.
36#[derive(Debug, Clone)]
37pub struct Biconnectivity {
38 bridges: Edges,
39 articulation_points: Vec<u32>,
40 blocks: EdgePartition,
41}
42
43impl Biconnectivity {
44 /// The body of [`components::biconnectivity_of`](crate::components::biconnectivity_of).
45 pub(crate) fn of(graph: &BiAdjacentGraph) -> Self {
46 let mut finder = BlockFinder::new(graph);
47 finder.run();
48 Self {
49 bridges: Edges::sorted_edges(
50 graph,
51 &finder.bridge_sources,
52 &finder.bridge_targets,
53 &finder.bridge_edge_indices,
54 finder.bridge_sources.len(),
55 false,
56 ),
57 articulation_points: flagged_nodes(&finder.is_articulation),
58 blocks: {
59 let groups =
60 parent_forest::group_indices(&finder.block_of_edge, finder.block_count);
61 EdgePartition::new(finder.block_of_edge, groups.members, groups.start)
62 },
63 }
64 }
65
66 /// Returns the bridges, in edge index order.
67 ///
68 /// Of a bridge stored in both directions, only the edge from the lower to the higher node ID is
69 /// listed; [`blocks`](Self::blocks) puts the other direction in the same block.
70 ///
71 /// **Time:** O(1).
72 pub fn bridges(&self) -> &Edges {
73 &self.bridges
74 }
75
76 /// Returns the articulation points, in ascending order.
77 ///
78 /// **Time:** O(1).
79 pub fn articulation_points(&self) -> SortedIntView<'_> {
80 SortedIntView::new(&self.articulation_points)
81 }
82
83 /// Returns the blocks, as a partition of the edges.
84 ///
85 /// Each block is a group of the partition: `blocks().get(e)` returns the block of edge `e`, and
86 /// `blocks().edges_of(block)` the edges of a block. Self-loops are in no block and map to `None`, so
87 /// [`is_partial`](crate::IndexMapping::is_partial) returns `true` exactly if the graph has self-loops.
88 /// Which block gets which group ID is not specified, but the same graph always yields the same group
89 /// IDs.
90 ///
91 /// **Time:** O(1).
92 pub fn blocks(&self) -> &EdgePartition {
93 &self.blocks
94 }
95}
96
97/// The nodes whose flag is set, ascending; [`StrongConnectivity`](crate::StrongConnectivity)
98/// uses it as well.
99pub(crate) fn flagged_nodes(is_flagged: &[bool]) -> Vec<u32> {
100 // Counted first, as in Java, so that the result has exactly its length.
101 let mut nodes = Vec::with_capacity(is_flagged.iter().filter(|&&flag| flag).count());
102 nodes.extend((0..is_flagged.len() as u32).filter(|&node| is_flagged[node as usize]));
103 nodes
104}
105
106/// Hopcroft-Tarjan biconnectivity on an explicit stack.
107///
108/// Neighbors are read as undirected by merging a node's out- and in-adjacency, both sorted
109/// ascending, emitting each neighbor once. The merge is also where a block's edge indices come
110/// from: for one undirected edge it sees the out-adjacency slot - already an edge index - and the
111/// in-adjacency slot in the same step, and the latter translates to an edge index through
112/// [`EdgeMapping::for_transposed`]. Collapsing the reciprocal pair removes the usual
113/// complication around the edge back to the depth-first parent: the parent appears exactly once in
114/// the merged sequence, so skipping it needs no parent-edge identity.
115///
116/// Per-node state lives in arrays rather than in stack frames, because a node is on the stack at
117/// most once; the stack itself is a plain array of node IDs. The edge stack grows on demand.
118struct BlockFinder<'g> {
119 out_adjacency: &'g [u32],
120 out_adjacency_start: &'g [u32],
121 in_adjacency: &'g [u32],
122 in_adjacency_start: &'g [u32],
123 /// In-adjacency slot to the edge index of the same edge.
124 in_slot_to_edge: Box<[u32]>,
125 /// Discovery time, 0 until the node is reached; counting starts at 1.
126 disc: Vec<u32>,
127 low: Vec<u32>,
128 dfs_parent: Vec<u32>,
129 /// Edge-stack height before the tree edge into this node was pushed.
130 block_mark: Vec<u32>,
131 out_cursor: Vec<u32>,
132 in_cursor: Vec<u32>,
133 dfs_stack: Vec<u32>,
134 edge_stack: Vec<u32>,
135 edge_top: usize,
136 is_articulation: Vec<bool>,
137 /// Bridges as parallel lists of source, target and edge index, each a stored edge.
138 bridge_sources: Vec<u32>,
139 bridge_targets: Vec<u32>,
140 bridge_edge_indices: Vec<u32>,
141 /// Edge index to block ID, [`NONE`] for a self-loop.
142 block_of_edge: Vec<u32>,
143 block_count: u32,
144 timer: u32,
145 /// Neighbor found by `advance`, with the slots of its two directions or [`NONE`].
146 pending_node: u32,
147 pending_out_edge: u32,
148 pending_in_slot: u32,
149}
150
151impl<'g> BlockFinder<'g> {
152 fn new(graph: &'g BiAdjacentGraph) -> Self {
153 let n = graph.node_count() as usize;
154 let m = graph.edge_count() as usize;
155 Self {
156 out_adjacency: graph.out_adjacency(),
157 out_adjacency_start: graph.out_adjacency_start(),
158 in_adjacency: graph.in_adjacency(),
159 in_adjacency_start: graph.in_adjacency_start(),
160 in_slot_to_edge: EdgeMapping::for_transposed(graph).into_array(),
161 disc: vec![0; n],
162 low: vec![0; n],
163 dfs_parent: vec![0; n],
164 block_mark: vec![0; n],
165 out_cursor: vec![0; n],
166 in_cursor: vec![0; n],
167 dfs_stack: vec![0; n],
168 // Sized like dfs_frames::initial: one slot per edge, but at least 16 and at most 1024.
169 edge_stack: vec![0; m.clamp(16, 1024)],
170 edge_top: 0,
171 is_articulation: vec![false; n],
172 bridge_sources: Vec::new(),
173 bridge_targets: Vec::new(),
174 bridge_edge_indices: Vec::new(),
175 block_of_edge: vec![NONE; m],
176 block_count: 0,
177 timer: 0,
178 pending_node: 0,
179 pending_out_edge: NONE,
180 pending_in_slot: NONE,
181 }
182 }
183
184 fn run(&mut self) {
185 let n = self.disc.len();
186 for root in 0..n {
187 if self.disc[root] != 0 {
188 continue;
189 }
190 self.discover(root as u32, NONE);
191 self.dfs_stack[0] = root as u32;
192 let mut top = 0usize;
193 let mut root_children = 0u32;
194
195 'outer: loop {
196 let u = self.dfs_stack[top];
197 while self.advance(u) {
198 let v = self.pending_node;
199 // The one occurrence of the parent is the tree edge back up; it is pushed.
200 if v == self.dfs_parent[u as usize] {
201 continue;
202 }
203 if self.disc[v as usize] == 0 {
204 let mark = self.edge_top as u32;
205 self.push_pending_edges();
206 self.discover(v, u);
207 self.block_mark[v as usize] = mark;
208 if u as usize == root {
209 root_children += 1;
210 }
211 top += 1;
212 self.dfs_stack[top] = v;
213 continue 'outer;
214 }
215 if self.disc[v as usize] < self.disc[u as usize] {
216 // Back edge to an ancestor. Undirected depth-first search has no cross
217 // edges, so a finished descendant was handled from its own side.
218 self.push_pending_edges();
219 if self.disc[v as usize] < self.low[u as usize] {
220 self.low[u as usize] = self.disc[v as usize];
221 }
222 }
223 }
224
225 let parent = self.dfs_parent[u as usize];
226 if parent != NONE {
227 let (u, p) = (u as usize, parent as usize);
228 if self.low[u] < self.low[p] {
229 self.low[p] = self.low[u];
230 }
231 if self.low[u] >= self.disc[p] {
232 let mark = self.block_mark[u] as usize;
233 if self.low[u] > self.disc[p] {
234 self.add_bridge(parent, u as u32, mark);
235 }
236 self.close_block(mark);
237 // The root is an articulation point only with two or more subtrees.
238 if p != root {
239 self.is_articulation[p] = true;
240 }
241 }
242 }
243 if top == 0 {
244 break;
245 }
246 top -= 1;
247 }
248
249 if root_children >= 2 {
250 self.is_articulation[root] = true;
251 }
252 }
253 }
254
255 /// Discovers `node` as a child of `parent` and initializes its merge cursors.
256 fn discover(&mut self, node: u32, parent: u32) {
257 let v = node as usize;
258 self.timer += 1;
259 self.disc[v] = self.timer;
260 self.low[v] = self.timer;
261 self.dfs_parent[v] = parent;
262 self.out_cursor[v] = self.out_adjacency_start[v];
263 self.in_cursor[v] = self.in_adjacency_start[v];
264 }
265
266 /// Advances `node`'s merge cursors to its next undirected neighbor, skipping self-loops, and
267 /// reports it in `pending_node`. Returns `false` once the neighbors are exhausted.
268 fn advance(&mut self, node: u32) -> bool {
269 let v = node as usize;
270 let mut out = self.out_cursor[v] as usize;
271 let out_end = self.out_adjacency_start[v + 1] as usize;
272 let mut inn = self.in_cursor[v] as usize;
273 let in_end = self.in_adjacency_start[v + 1] as usize;
274
275 while out < out_end || inn < in_end {
276 let out_neighbor = if out < out_end {
277 self.out_adjacency[out]
278 } else {
279 u32::MAX
280 };
281 let in_neighbor = if inn < in_end {
282 self.in_adjacency[inn]
283 } else {
284 u32::MAX
285 };
286 let (neighbor, out_edge, in_slot);
287 if out_neighbor < in_neighbor {
288 neighbor = out_neighbor;
289 out_edge = out as u32;
290 in_slot = NONE;
291 out += 1;
292 } else if in_neighbor < out_neighbor {
293 neighbor = in_neighbor;
294 out_edge = NONE;
295 in_slot = inn as u32;
296 inn += 1;
297 } else {
298 // Both directions of one undirected edge; both indices belong to the same block.
299 neighbor = out_neighbor;
300 out_edge = out as u32;
301 in_slot = inn as u32;
302 out += 1;
303 inn += 1;
304 }
305 if neighbor == node {
306 continue; // self-loop: in no block, never a bridge
307 }
308 self.out_cursor[v] = out as u32;
309 self.in_cursor[v] = inn as u32;
310 self.pending_node = neighbor;
311 self.pending_out_edge = out_edge;
312 self.pending_in_slot = in_slot;
313 return true;
314 }
315 self.out_cursor[v] = out as u32;
316 self.in_cursor[v] = inn as u32;
317 false
318 }
319
320 /// Pushes the edge indices of the pending undirected edge - one per stored direction, so a
321 /// reciprocal pair pushes both and lands in one block.
322 fn push_pending_edges(&mut self) {
323 if self.pending_out_edge != NONE {
324 self.push_edge(self.pending_out_edge);
325 }
326 if self.pending_in_slot != NONE {
327 self.push_edge(self.in_slot_to_edge[self.pending_in_slot as usize]);
328 }
329 }
330
331 fn push_edge(&mut self, edge_index: u32) {
332 if self.edge_top == self.edge_stack.len() {
333 // Every non-self-loop edge is pushed at most once, so the edge count is the cap.
334 let grown = (self.edge_top << 1).min(self.block_of_edge.len());
335 // Exactly `grown`, as Java's Arrays.copyOf: resize alone rounds up to a doubling.
336 self.edge_stack.reserve_exact(grown - self.edge_top);
337 self.edge_stack.resize(grown, 0);
338 }
339 self.edge_stack[self.edge_top] = edge_index;
340 self.edge_top += 1;
341 }
342
343 /// Records the bridge `parent - child` before its block closes. Every block below the child
344 /// is closed already, so the edges above `mark` are exactly the one or two stored directions of
345 /// the bridge, pushed `parent -> child` first. A bridge stored both ways is reported from the
346 /// lower node ID.
347 fn add_bridge(&mut self, parent: u32, child: u32, mark: usize) {
348 let pushed = self.edge_top - mark;
349 debug_assert!(pushed == 1 || pushed == 2);
350 let edge = if pushed == 2 && parent > child {
351 self.edge_stack[mark + 1]
352 } else {
353 self.edge_stack[mark]
354 };
355 let target = self.out_adjacency[edge as usize];
356 growth::push(
357 &mut self.bridge_sources,
358 if target == child { parent } else { child },
359 );
360 growth::push(&mut self.bridge_targets, target);
361 growth::push(&mut self.bridge_edge_indices, edge);
362 }
363
364 /// Turns the edges above `mark` into one block.
365 fn close_block(&mut self, mark: usize) {
366 let block = self.block_count;
367 self.block_count += 1;
368 while self.edge_top > mark {
369 self.edge_top -= 1;
370 self.block_of_edge[self.edge_stack[self.edge_top] as usize] = block;
371 }
372 }
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn flagged_nodes_have_exactly_their_length() {
381 let nodes = flagged_nodes(&[false, true, true, false, true]);
382 assert_eq!(nodes, [1, 2, 4]);
383 // Java counts first and fills an array of that length.
384 assert_eq!(nodes.capacity(), 3);
385 }
386}