-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtopological_sort.go
56 lines (50 loc) · 1.13 KB
/
topological_sort.go
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
package graphs
import (
"container/list"
"errors"
)
var ErrNoDAG = errors.New("graphs: graph is not a DAG")
func TopologicalSort[T Vertex](g *Graph[T]) (topologicalOrder *list.List, topologicalClasses map[T]int, err error) {
inEdges := make(map[T]int)
g.EachEdge(func(e Edge[T], _ func()) {
if _, ok := inEdges[e.Start]; !ok {
inEdges[e.Start] = 0
}
if _, ok := inEdges[e.End]; ok {
inEdges[e.End]++
} else {
inEdges[e.End] = 1
}
})
removeEdgesFromVertex := func(v T) {
g.EachHalfedge(v, func(outEdge Halfedge[T], _ func()) {
neighbor := outEdge.End
inEdges[neighbor]--
})
}
topologicalClasses = make(map[T]int)
topologicalOrder = list.New()
tClass := 0
for len(inEdges) > 0 {
topClass := []T{}
for v, inDegree := range inEdges {
if inDegree == 0 {
topClass = append(topClass, v)
topologicalClasses[v] = tClass
}
}
if len(topClass) == 0 {
err = ErrNoDAG
topologicalClasses = make(map[T]int)
topologicalOrder = list.New()
return
}
for _, v := range topClass {
removeEdgesFromVertex(v)
delete(inEdges, v)
topologicalOrder.PushBack(v)
}
tClass++
}
return
}