-
Notifications
You must be signed in to change notification settings - Fork 0
/
dag.go
131 lines (114 loc) · 2.48 KB
/
dag.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package dag
import (
"errors"
)
type DAG[Node comparable] struct {
nodes []Node
requires map[Node][]Node
topoSort [][]Node
}
var InvalidDAG = errors.New("invalid DAG")
func NewDAG[Node comparable](requires map[Node][]Node) (*DAG[Node], error) {
ts, err := NewTopoSort(requires)
if err != nil {
return nil, err
}
nodes := make([]Node, 0, len(requires))
for i := range ts {
nodes = append(nodes, ts[i]...)
}
dag := &DAG[Node]{
nodes: nodes,
requires: copyRequires(requires),
topoSort: ts,
}
return dag, nil
}
func (d *DAG[Node]) TopoSort() [][]Node {
return copyTopoSort(d.topoSort)
}
func (d *DAG[Node]) Nodes() []Node {
return copyNodes(d.nodes)
}
func (d *DAG[Node]) Solve(problem []Node) [][]Node {
needMap := make(map[Node]bool)
for len(problem) > 0 {
var next []Node
for _, node := range problem {
needMap[node] = true
for _, r := range d.requires[node] {
if !needMap[r] {
next = append(next, r)
}
}
}
problem = next
}
var solution [][]Node
for _, nodes := range d.topoSort {
var rs []Node
for _, node := range nodes {
if needMap[node] {
rs = append(rs, node)
}
}
if len(rs) > 0 {
solution = append(solution, rs)
}
}
return solution
}
func NewTopoSort[Node comparable](requires map[Node][]Node) ([][]Node, error) {
var ts [][]Node
stageMap := make(map[Node]int, len(requires))
for stage := 0; len(stageMap) < len(requires); stage++ {
var nodes []Node
for node, rs := range requires {
if _, ok := stageMap[node]; ok {
continue
}
var notReady []Node
for _, r := range rs {
if _, ok := stageMap[r]; !ok {
notReady = append(notReady, r)
}
}
if len(notReady) == 0 {
nodes = append(nodes, node)
}
}
// check got empty
if len(nodes) == 0 {
return nil, InvalidDAG
}
for _, node := range nodes {
stageMap[node] = stage
}
ts = append(ts, nodes)
}
return ts, nil
}
func copyRequires[Node comparable](requires map[Node][]Node) map[Node][]Node {
requires2 := make(map[Node][]Node, len(requires))
for node, rs := range requires {
if len(rs) > 0 {
rs2 := make([]Node, len(rs))
copy(rs2, rs)
requires2[node] = rs2
}
}
return requires2
}
func copyTopoSort[Node comparable](ts [][]Node) [][]Node {
ts2 := make([][]Node, len(ts))
for i := range ts {
ts2[i] = make([]Node, len(ts[i]))
copy(ts2[i], ts[i])
}
return ts2
}
func copyNodes[Node comparable](nodes []Node) []Node {
nodes2 := make([]Node, len(nodes))
copy(nodes2, nodes)
return nodes2
}