-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_test.go
127 lines (116 loc) · 1.9 KB
/
graph_test.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
package dagRun
import (
"fmt"
"testing"
)
type StringNode struct {
Data string
}
func (s *StringNode) Name() string {
return s.Data
}
var nodes = []*StringNode{
{"A"},
{"B"},
{"C"},
{"D"},
{"E"},
}
var edges = [...][2]int{
{1, 0},
{1, 4},
{1, 3},
{0, 2},
{0, 3},
{2, 3},
{3, 4},
}
var g = func() *Graph {
graph := NewGraph()
for _, node := range nodes {
graph.AddNode(node)
}
for _, edge := range edges {
graph.AddEdge(nodes[edge[0]], nodes[edge[1]])
}
return graph
}
func ExampleNewGraph() {
fmt.Println(g().String())
// OUTPUT:
//[A]-> [C,D,]
//[B]-> [A,E,D,]
//[C]-> [D,]
//[D]-> [E,]
//[E]-> []
}
func ExampleGraph_DOT() {
fmt.Println(g().DOT())
// OUTPUT:
//digraph G {
//
//"start" [color="green",shape=doublecircle]
//"end" [color="red",shape=doublecircle]
//
//"A" -> {"C","D"}
//"B" -> {"A","D","E"}
//"C" -> {"D"}
//"D" -> {"E"}
//"E" -> {"end"}
//"start" -> {"B"}
//}
}
func ExampleGraph_DFS() {
graph := g()
// graph.AddEdge(nodes[4], nodes[0])
err := graph.DFS(func(node Node) error {
fmt.Println(node.Name())
return nil
})
if err != nil {
fmt.Println("err ", err)
}
// OUTPUT:
//A
//C
//D
//E
//B
}
func TestCircleBFS(t *testing.T) {
graph := g()
graph.AddEdge(nodes[4], nodes[0])
err := graph.BFS(func(node Node) error {
fmt.Println(node.Name())
return nil
})
want := "graph has circle in nodes:[A C D E]"
if err.Error() != want {
t.Errorf("want err:%s but get:%+v", want, err)
}
}
func TestCircleDFS(t *testing.T) {
graph := g()
graph.AddEdge(nodes[4], nodes[0])
err := graph.DFS(func(node Node) error {
fmt.Println(node.Name())
return nil
})
want := "graph has circle, cur node:E ,next node:A"
if err.Error() != want {
t.Errorf("want err:%s but get:%v", want, err)
}
}
func ExampleGraph_BFS() {
graph := g()
_ = graph.BFS(func(node Node) error {
fmt.Println(node.Name())
return nil
})
// OUTPUT:
//B
//A
//C
//D
//E
}