forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopological_sort.go
60 lines (49 loc) · 1.24 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
57
58
59
60
package graph
import (
"container/list"
"errors"
)
// VertexWithIngress is a Vertex with the count of vertices that connect to it.
type VertexWithIngress struct {
// Val is the value of the vertex
Val any
// The edges that this Vertex is connected to
Edges []*VertexWithIngress
// Ingress is the number of vertices that connect to this vertex
Ingress int
}
// ErrNotADAG occurs when a graph is not a Direct Acyclic Graph - DAG.
var ErrNotADAG = errors.New("graph is not a Direct Acyclic Graph - DAG")
// TopologicalSort solves the problem in O(n) time and O(n) space.
func TopologicalSort(graph []*VertexWithIngress) ([]*VertexWithIngress, error) {
var (
output = []*VertexWithIngress{}
queue = list.New()
i = 0
)
for _, vertex := range graph {
for _, neighbor := range vertex.Edges {
neighbor.Ingress++
}
}
for _, vertex := range graph {
if vertex.Ingress == 0 {
queue.PushBack(vertex)
}
}
for queue.Len() != 0 {
i++
vertex := queue.Remove(queue.Front()).(*VertexWithIngress)
output = append(output, vertex)
for _, neighbor := range vertex.Edges {
neighbor.Ingress--
if neighbor.Ingress == 0 {
queue.PushBack(neighbor)
}
}
}
if i != len(graph) {
return nil, ErrNotADAG
}
return output, nil
}