Skip to main content

strongly_connected_components

Function strongly_connected_components 

Source
pub fn strongly_connected_components<G: Graph>(graph: &G) -> Vec<usize>
Expand description

Tarjan’s algorithm for strongly connected components.

Returns a component label for each node (nodes in the same SCC share a label). Labels are assigned in reverse topological order of the condensation DAG: component 0 is a sink SCC, the last component is a source SCC.

The neighbors function of the Graph trait is interpreted as out-neighbors (directed edges). For undirected graphs, each SCC is a connected component.

Time: O(V + E), single DFS pass.

use graphops::graph::Graph;
use graphops::partition::strongly_connected_components;

struct G(Vec<Vec<usize>>);
impl Graph for G {
    fn node_count(&self) -> usize { self.0.len() }
    fn neighbors(&self, n: usize) -> Vec<usize> { self.0[n].clone() }
}

// A single 3-cycle: 0 -> 1 -> 2 -> 0
let g = G(vec![vec![1], vec![2], vec![0]]);
let labels = strongly_connected_components(&g);
assert_eq!(labels[0], labels[1]);
assert_eq!(labels[1], labels[2]);