-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.go
70 lines (58 loc) · 1.2 KB
/
basic.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
package graph
type BasicEdge struct {
weight int
neighbor Node
}
func (b *BasicEdge) Neighbor() Node {
return b.neighbor
}
func (b *BasicEdge) Weight() int {
return b.weight
}
func NewBasicEdge(weight int, neighbor Node) *BasicEdge {
return &BasicEdge{weight, neighbor}
}
type BasicNode struct {
id string
edges []Edge
}
func (b *BasicNode) AddEdge(edge Edge) {
b.edges = append(b.edges, edge)
}
func (b *BasicNode) Edges() []Edge {
return b.edges
}
type BasicGraph struct {
nodes map[string]*BasicNode
}
func NewBasicGraph() *BasicGraph {
return &BasicGraph{make(map[string]*BasicNode)}
}
func (b *BasicGraph) GetNode(id string) *BasicNode {
return b.nodes[id]
}
func (b *BasicGraph) AddDirectedEdge(id1, id2 string, weight int) {
node1, found := b.nodes[id1]
if !found {
node1 = &BasicNode{id: id1}
if b.nodes == nil {
b.nodes = make(map[string]*BasicNode)
}
b.nodes[id1] = node1
}
node2, found := b.nodes[id2]
if !found {
node2 = &BasicNode{id: id2}
b.nodes[id2] = node2
}
node1.AddEdge(&BasicEdge{weight, node2})
}
func (b *BasicGraph) Nodes() []Node {
nodes := make([]Node, len(b.nodes))
i := 0
for _, node := range b.nodes {
nodes[i] = node
i++
}
return nodes
}