| 1 |
package graph |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
func TopSort(g Iterator) (order []int, ok bool) { |
| 9 |
order, ok = topsort(g, true) |
| 10 |
return |
| 11 |
} |
| 12 |
|
| 13 |
|
| 14 |
func Acyclic(g Iterator) bool { |
| 15 |
_, acyclic := topsort(g, false) |
| 16 |
return acyclic |
| 17 |
} |
| 18 |
|
| 19 |
|
| 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 |
|
| 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 |
} |