forked from shellfly/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathedge_weighted_digraph.go
85 lines (74 loc) · 1.64 KB
/
edge_weighted_digraph.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
package algs4
import (
"fmt"
"github.com/shellfly/algo/stdin"
)
// EdgeWeightedDigraph ...
type EdgeWeightedDigraph struct {
v, e int
adj []*Bag
}
// NewEdgeWeightedDigraph ...
func NewEdgeWeightedDigraph(in *stdin.In) *EdgeWeightedDigraph {
v := in.ReadInt()
adj := make([]*Bag, v)
for i := 0; i < v; i++ {
adj[i] = NewBag()
}
g := &EdgeWeightedDigraph{v: v, e: 0, adj: adj}
e := in.ReadInt()
for i := 0; i < e; i++ {
v, w, weight := in.ReadInt(), in.ReadInt(), in.ReadFloat32()
g.AddEdge(NewDirectedEdge(v, w, weight))
}
return g
}
// NewEdgeWeightedDigraphV ...
func NewEdgeWeightedDigraphV(v int) *EdgeWeightedDigraph {
adj := make([]*Bag, v)
for i := 0; i < v; i++ {
adj[i] = NewBag()
}
return &EdgeWeightedDigraph{v: v, e: 0, adj: adj}
}
// V ...
func (g *EdgeWeightedDigraph) V() int {
return g.v
}
// E ...
func (g *EdgeWeightedDigraph) E() int {
return g.e
}
// AddEdge ...
func (g *EdgeWeightedDigraph) AddEdge(e *DirectedEdge) {
g.adj[e.From()].Add(e)
g.e++
}
// Adj ...
func (g *EdgeWeightedDigraph) Adj(v int) []*DirectedEdge {
var items []*DirectedEdge
for _, item := range g.adj[v].Slice() {
items = append(items, item.(*DirectedEdge))
}
return items
}
// Edges ...
func (g *EdgeWeightedDigraph) Edges() (edges []*DirectedEdge) {
for v := 0; v < g.v; v++ {
for _, e := range g.Adj(v) {
edges = append(edges, e)
}
}
return
}
func (g *EdgeWeightedDigraph) String() string {
s := fmt.Sprintf("%d vertices, %d edges\n", g.v, g.e)
for i := 0; i < g.v; i++ {
var adjs string
for _, e := range g.Adj(i) {
adjs = fmt.Sprintf("%s %s ", adjs, e)
}
s += fmt.Sprintf("%d: %s\n", i, adjs)
}
return s
}