Debian Codegraph @

strong.go

raw symbols SCIP
1 package graph
2
3 // StrongComponents produces a partition of g's vertices into its
4 // strongly connected components.
5 //
6 // A component is strongly connected if all its vertices are reachable
7 // from every other vertex in the component.
8 // Each vertex of the graph appears in exactly one of the strongly
9 // connected components, and any vertex that is not on a directed cycle
10 // forms a strongly connected component all by itself.
11 func StrongComponents(g Iterator) [][]int {
12 n := g.Order()
13 s := &scc{
14 graph: g,
15 visited: make([]bool, n),
16 lowLink: make([]int, n),
17 }
18 components := [][]int{}
19 for v := range s.visited {
20 if !s.visited[v] {
21 components = s.append(components, v)
22 }
23 }
24 return components
25 }
26
27 // Tarjan's algorithm
28 type scc struct {
29 graph Iterator
30 visited []bool
31 stack []int
32 lowLink []int
33 time int
34 }
35
36 // Make a depth-first search starting at v and append all strongly
37 // connected components of the visited subgraph to comps.
38 func (s *scc) append(components [][]int, v int) [][]int {
39 // A vertex remains on this stack after it has been visited iff
40 // there is a path from it to some vertex earlier on the stack.
41 s.stack = append(s.stack, v)
42
43 // lowLink[v] is the smallest vertex known to be reachable from v.
44 s.lowLink[v] = s.time
45 s.time++
46
47 newComponent := true
48 s.visited[v] = true
49 s.graph.Visit(v, func(w int, _ int64) (skip bool) {
50 if !s.visited[w] {
51 components = s.append(components, w)
52 }
53 if s.lowLink[v] > s.lowLink[w] {
54 s.lowLink[v] = s.lowLink[w]
55 newComponent = false
56 }
57 return
58 })
59 if !newComponent {
60 return components
61 }
62 var comp []int
63 for {
64 n := len(s.stack) - 1
65 w := s.stack[n]
66 s.stack = s.stack[:n]
67 s.lowLink[w] = int(^uint(0) >> 1) // maxint
68 comp = append(comp, w)
69 if v == w {
70 return append(components, comp)
71 }
72 }
73 }