-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdag_test.go
More file actions
50 lines (44 loc) · 893 Bytes
/
dag_test.go
File metadata and controls
50 lines (44 loc) · 893 Bytes
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
package main
import (
"fmt"
"github.com/eapache/queue"
"testing"
"time"
)
func TestDag(t *testing.T) {
_, root := NewDAG()
all := BFS(root)
doTasks(all)
}
//广度遍历
func BFS(root *Vertex) []*Vertex {
q := queue.New()
q.Add(root)
visited := make(map[string]*Vertex)
all := make([]*Vertex, 0)
for q.Length() > 0 {
qSize := q.Length()
for i := 0; i < qSize; i++ {
//pop vertex
currVert := q.Remove().(*Vertex)
if _, ok := visited[currVert.Key]; ok {
continue
}
visited[currVert.Key] = currVert
all = append([]*Vertex{currVert}, all...)
for _, val := range currVert.Children {
if _, ok := visited[val.Key]; !ok {
q.Add(val) //add child
}
}
}
}
return all
}
//并发执行
func doTasks(vertexs []*Vertex) {
for _, v := range vertexs {
time.Sleep(5 * time.Second)
fmt.Printf("do %v, result is %v \n", v.Key, v.Value)
}
}