-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdag1_test.go
More file actions
66 lines (57 loc) · 1.2 KB
/
dag1_test.go
File metadata and controls
66 lines (57 loc) · 1.2 KB
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
package main
import (
"fmt"
"github.com/eapache/queue"
"sync"
"testing"
"time"
)
func TestDagNew(t *testing.T) {
_, root := NewDAG()
all := BFSNew(root)
for _, layer := range all {
fmt.Println("------------------")
doTasksNew(layer)
}
}
//广度遍历 返回双层结构
func BFSNew(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()
tmp := make([]*Vertex, 0)
for i := 0; i < qSize; i++ {
//pop vertex
currVert := q.Remove().(*Vertex)
if _, ok := visited[currVert.Key]; ok {
continue
}
visited[currVert.Key] = currVert
tmp = append(tmp, currVert)
//fmt.Println(level, currVert.Key, currVert.Value)
for _, val := range currVert.Children {
if _, ok := visited[val.Key]; !ok {
q.Add(val) //add child
}
}
}
all = append([][]*Vertex{tmp}, all...)
}
return all
}
//并发执行
func doTasksNew(vertexs []*Vertex) {
var wg sync.WaitGroup
for _, v := range vertexs {
wg.Add(1)
go func(v *Vertex) {
defer wg.Done()
time.Sleep(5 * time.Second)
fmt.Printf("do %v, result is %v \n", v.Key, v.Value)
}(v) //notice
}
wg.Wait()
}