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
use crateVisitMap;
use Vec;
use crate;
/// Renamed to `kosaraju_scc`.
/// Compute the *strongly connected components* using [Kosaraju's algorithm][1].
///
/// This implementation is iterative and does two passes over the nodes.
///
/// # Arguments
/// * `g`: a directed or undirected graph.
///
/// # Returns
/// Return a vector where each element is a strongly connected component (scc).
/// The order of node ids within each scc is arbitrary, but the order of
/// the sccs is their postorder (reverse topological sort).
///
/// For an undirected graph, the sccs are simply the connected components.
///
/// # Complexity
/// * Time complexity: **O(|V| + |E|)**.
/// * Auxiliary space: **O(|V|)**.
///
/// where **|V|** is the number of nodes and **|E|** is the number of edges.
///
/// # Examples
///
/// ```rust
/// use petgraph::Graph;
/// use petgraph::algo::kosaraju_scc;
/// use petgraph::prelude::*;
///
/// let mut graph: Graph<i32, (), Directed> = Graph::new();
/// let a = graph.add_node(1);
/// let b = graph.add_node(2);
/// let c = graph.add_node(3);
/// let d = graph.add_node(4);
/// let e = graph.add_node(5);
/// let f = graph.add_node(6);
///
/// graph.extend_with_edges(&[
/// (a, b), (b, c), (c, a), // First SCC: a -> b -> c -> a
/// (d, e), (e, f), (f, d), // Second SCC: d -> e -> f -> d
/// (c, d), // Connection between SCCs
/// ]);
///
/// // Graph structure:
/// // a ---> b e ---> f
/// // ↑ ↓ ↑ |
/// // └---- c ---> d <----┘
///
/// let sccs = kosaraju_scc(&graph);
/// assert_eq!(sccs.len(), 2); // Two strongly connected components
///
/// // Each SCC contains 3 nodes
/// assert_eq!(sccs[0].len(), 3);
/// assert_eq!(sccs[1].len(), 3);
/// ```
///
/// For a simple directed acyclic graph (DAG):
///
/// ```rust
/// use petgraph::Graph;
/// use petgraph::algo::kosaraju_scc;
/// use petgraph::prelude::*;
///
/// let mut dag: Graph<&str, (), Directed> = Graph::new();
/// let a = dag.add_node("A");
/// let b = dag.add_node("B");
/// let c = dag.add_node("C");
///
/// dag.extend_with_edges(&[(a, b), (b, c)]);
/// // A -> B -> C
///
/// let sccs = kosaraju_scc(&dag);
/// assert_eq!(sccs.len(), 3); // Each node is its own SCC
///
/// // Each SCC contains exactly one node
/// for scc in &sccs {
/// assert_eq!(scc.len(), 1);
/// }
/// ```
///
/// [1]: https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm