Skip to main content

graphity_core/
strong_connectivity.rs

1use crate::array_limits::check_node_count;
2use crate::biconnectivity::flagged_nodes;
3use crate::{
4    BiAdjacentGraph, Dominators, Edges, NONE, Sccs, SortedIntView, dfs_preorder, growth,
5    parent_forest,
6};
7
8/// The strong bridges and strong articulation points of a graph, as
9/// [`components::strong_connectivity_of`](crate::components::strong_connectivity_of) returns them.
10///
11/// A strong bridge is an edge whose removal increases the number of SCCs (strongly connected
12/// components), and a strong articulation point is a node whose removal does the same. Strong
13/// bridges lie inside SCCs of two or more nodes. Strong articulation points lie inside SCCs of
14/// three or more nodes, since without one node of an SCC of two, the other still forms an SCC. So a
15/// graph without cycles has neither, and a self-loop is never a strong bridge.
16///
17/// The edges are followed in their direction, as by
18/// [`components::sccs_of`](crate::components::sccs_of): the edges `a -> b` and `b -> a` are two
19/// edges, and both are strong bridges of the SCC they form.
20/// [`Biconnectivity`](crate::Biconnectivity) has the counterparts for a graph read as undirected.
21/// Here, in the control flow of the method `load`, the loop splits into several SCCs without
22/// `header`, `body` or `next`, but not without `then`:
23///
24/// <!-- example: connectivity.rs#strongConnectivity -->
25/// ```
26/// # use graphity_core::{BiAdjacentGraph, components};
27/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
28/// let strong = components::strong_connectivity_of(&BiAdjacentGraph::of(&cfg));
29/// let strong_bridges = strong.strong_bridges();
30/// // strong_bridges: header -> body, body -> then, then -> next, next -> header
31/// let strong_articulation_points = strong.strong_articulation_points();
32/// // strong_articulation_points: [1, 2, 4] - header, body and next
33/// # assert_eq!(strong_bridges.source_nodes(), [1, 2, 3, 4]);
34/// # assert_eq!(strong_bridges.target_nodes(), [2, 3, 4, 1]);
35/// # assert_eq!(strong_articulation_points, [1, 2, 4]);
36/// ```
37///
38/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
39///
40/// **Memory:** up to 28 x node_count bytes.
41#[derive(Debug, Clone)]
42pub struct StrongConnectivity {
43    strong_bridges: Edges,
44    strong_articulation_points: Vec<u32>,
45}
46
47impl StrongConnectivity {
48    /// The body of [`components::strong_connectivity_of`](crate::components::strong_connectivity_of),
49    /// following Italiano, Laura and Santaroni: within an SCC and for any node `r` of it, an edge is a
50    /// strong bridge exactly if it is a bridge of the flow graph rooted at `r` or of its transposed graph,
51    /// and a node other than `r` is a strong articulation point exactly if it dominates another node in
52    /// one of the two. Whether `r` itself is one is a separate check: the rest of its SCC stays strongly
53    /// connected or not.
54    pub(crate) fn of(graph: &BiAdjacentGraph) -> Self {
55        let n = graph.node_count();
56        // The dominators below allow one node less than Tarjan's algorithm: reject before it runs.
57        check_node_count(n, dfs_preorder::MAX_NODE_COUNT, "strong_connectivity_of");
58        let n = n as usize;
59        let sccs = Sccs::of(graph);
60        let scc_count = sccs.scc_count() as usize;
61        let scc_of = sccs.group_array();
62        let (members, member_start) = sccs.member_arrays();
63
64        // One entry per component, its first member: sink components first for the graph,
65        // source components first for its transpose, so every search stays in its component.
66        let sinks_first: Vec<u32> = (0..scc_count)
67            .map(|c| members[member_start[c] as usize])
68            .collect();
69        let sources_first: Vec<u32> = (0..scc_count)
70            .map(|c| members[member_start[scc_count - 1 - c] as usize])
71            .collect();
72        let forward = Dominators::within_blocks(graph, &sinks_first);
73        let backward = Dominators::within_blocks(&graph.transposed(), &sources_first);
74
75        let mut found = Found {
76            sources: Vec::new(),
77            targets: Vec::new(),
78            edge_indices: Vec::new(),
79            is_articulation: vec![false; n],
80        };
81        collect(
82            &forward,
83            graph.in_adjacency_start(),
84            graph.in_adjacency(),
85            scc_of,
86            false,
87            &mut found,
88        );
89        collect(
90            &backward,
91            graph.out_adjacency_start(),
92            graph.out_adjacency(),
93            scc_of,
94            true,
95            &mut found,
96        );
97        mark_entries(
98            graph,
99            scc_of,
100            members,
101            member_start,
102            &mut found.is_articulation,
103        );
104        Self {
105            strong_bridges: Edges::sorted_edges(
106                graph,
107                &found.sources,
108                &found.targets,
109                &found.edge_indices,
110                found.sources.len(),
111                true,
112            ),
113            strong_articulation_points: flagged_nodes(&found.is_articulation),
114        }
115    }
116
117    /// Returns the strong bridges, in edge index order.
118    ///
119    /// **Time:** O(1).
120    pub fn strong_bridges(&self) -> &Edges {
121        &self.strong_bridges
122    }
123
124    /// Returns the strong articulation points, in ascending order.
125    ///
126    /// **Time:** O(1).
127    pub fn strong_articulation_points(&self) -> SortedIntView<'_> {
128        SortedIntView::new(&self.strong_articulation_points)
129    }
130}
131
132/// The strong bridges, as parallel lists, and the strong articulation points found so far.
133struct Found {
134    sources: Vec<u32>,
135    targets: Vec<u32>,
136    edge_indices: Vec<u32>,
137    is_articulation: Vec<bool>,
138}
139
140/// Adds the bridges and non-trivial dominators of one flow graph, given by its immediate
141/// dominators and its in-adjacency. The edge `idom(v) -> v` is a bridge exactly if it exists - the
142/// immediate dominator need not be a predecessor - and `v` dominates every other predecessor of `v`
143/// in its component: every other way in already passes through `v`.
144///
145/// With `transposed`, the flow graph is the transpose, so a bridge `u -> v` found there is the edge
146/// `v -> u` of the graph, and the in-adjacency slot of `u` is the out-adjacency slot of the graph -
147/// its edge index.
148fn collect(
149    idom: &[u32],
150    in_start: &[u32],
151    inn: &[u32],
152    scc_of: &[u32],
153    transposed: bool,
154    found: &mut Found,
155) {
156    let n = idom.len();
157    let mut preorder_index = vec![0u32; n];
158    let mut order = vec![0u32; n];
159    let mut subtree_size = vec![0u32; n];
160    parent_forest::preorder(idom, &mut preorder_index, &mut order, &mut subtree_size);
161    for v in 0..n {
162        let u = idom[v];
163        if u == NONE {
164            continue;
165        }
166        if idom[u as usize] != NONE {
167            found.is_articulation[u as usize] = true;
168        }
169        let scc = scc_of[v];
170        let pre = preorder_index[v];
171        let size = subtree_size[v];
172        let mut from_idom = None;
173        let mut bridge = true;
174        let start = in_start[v] as usize;
175        for (offset, &w) in inn[start..in_start[v + 1] as usize].iter().enumerate() {
176            if w == u {
177                from_idom = Some((start + offset) as u32);
178            } else if scc_of[w as usize] == scc {
179                // v dominates w exactly if w lies in v's subtree, as in PreorderAncestry.
180                let index = preorder_index[w as usize];
181                if index < pre || index - pre >= size {
182                    bridge = false;
183                    break;
184                }
185            }
186        }
187        if let Some(slot) = from_idom.filter(|_| bridge) {
188            let v = v as u32;
189            growth::push(&mut found.sources, if transposed { v } else { u });
190            growth::push(&mut found.targets, if transposed { u } else { v });
191            growth::push(
192                &mut found.edge_indices,
193                if transposed { slot } else { NONE },
194            );
195        }
196    }
197}
198
199/// Marks the entry `r` of every component of three or more nodes if the rest of the component is
200/// not strongly connected: a search from another member, avoiding `r` and the edges leaving the
201/// component, misses a member forwards or backwards. Components of two nodes keep one node when
202/// either is removed, which is still strongly connected.
203fn mark_entries(
204    graph: &BiAdjacentGraph,
205    scc_of: &[u32],
206    members: &[u32],
207    member_start: &[u32],
208    is_articulation: &mut [bool],
209) {
210    let n = graph.node_count() as usize;
211    let out_start = graph.out_adjacency_start();
212    let out = graph.out_adjacency();
213    let in_start = graph.in_adjacency_start();
214    let inn = graph.in_adjacency();
215    let mut stamp = vec![0u32; n];
216    let mut queue = vec![0u32; n];
217    for c in 0..member_start.len() - 1 {
218        let size = member_start[c + 1] - member_start[c];
219        if size < 3 {
220            continue;
221        }
222        let entry = members[member_start[c] as usize];
223        let start = members[member_start[c] as usize + 1];
224        let rest = size - 1;
225        let c32 = c as u32;
226        // A fresh mark per component and direction, so the stamps are never cleared.
227        let mut search = |adj_start: &[u32], adj: &[u32], mark: u32| {
228            reached_avoiding(
229                adj_start, adj, scc_of, c32, entry, start, mark, &mut stamp, &mut queue,
230            )
231        };
232        if search(out_start, out, 2 * c32 + 1) < rest || search(in_start, inn, 2 * c32 + 2) < rest {
233            is_articulation[entry as usize] = true;
234        }
235    }
236}
237
238/// Breadth-first count of the members of component `scc` reached from `start` without `avoided`.
239#[allow(clippy::too_many_arguments)]
240fn reached_avoiding(
241    adj_start: &[u32],
242    adj: &[u32],
243    scc_of: &[u32],
244    scc: u32,
245    avoided: u32,
246    start: u32,
247    mark: u32,
248    stamp: &mut [u32],
249    queue: &mut [u32],
250) -> u32 {
251    stamp[avoided as usize] = mark;
252    stamp[start as usize] = mark;
253    queue[0] = start;
254    let mut head = 0usize;
255    let mut tail = 1usize;
256    while head < tail {
257        let u = queue[head] as usize;
258        head += 1;
259        for &v in &adj[adj_start[u] as usize..adj_start[u + 1] as usize] {
260            if stamp[v as usize] != mark && scc_of[v as usize] == scc {
261                stamp[v as usize] = mark;
262                queue[tail] = v;
263                tail += 1;
264            }
265        }
266    }
267    tail as u32
268}