Debian Codegraph @

top.go

raw symbols SCIP
1 package graph
2
3 // TopSort returns a topological ordering of the vertices in
4 // a directed acyclic graph; if the graph is not acyclic,
5 // no such ordering exists and ok is set to false.
6 //
7 // In a topological order v comes before w for every directed edge from v to w.
8 func TopSort(g Iterator) (order []int, ok bool) {
9 order, ok = topsort(g, true)
10 return
11 }
12
13 // Acyclic tells if g has no cycles.
14 func Acyclic(g Iterator) bool {
15 _, acyclic := topsort(g, false)
16 return acyclic
17 }
18
19 // Kahn's algorithm
20 func topsort(g Iterator, output bool) (order []int, acyclic bool) {
21 indegree := make([]int, g.Order())
22 for v := range indegree {
23 g.Visit(v, func(w int, _ int64) (skip bool) {
24 indegree[w]++
25 return
26 })
27 }
28
29 // Invariant: this queue holds all vertices with indegree 0.
30 var queue []int
31 for v, degree := range indegree {
32 if degree == 0 {
33 queue = append(queue, v)
34 }
35 }
36
37 order = []int{}
38 vertexCount := 0
39 for len(queue) > 0 {
40 v := queue[0]
41 queue = queue[1:]
42 if output {
43 order = append(order, v)
44 }
45 vertexCount++
46 g.Visit(v, func(w int, _ int64) (skip bool) {
47 indegree[w]--
48 if indegree[w] == 0 {
49 queue = append(queue, w)
50 }
51 return
52 })
53 }
54 if vertexCount != g.Order() {
55 return
56 }
57 acyclic = true
58 return
59 }