forked from shellfly/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
72 lines (62 loc) · 1.09 KB
/
graph.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
package algs4
import (
"fmt"
"github.com/shellfly/algo/stdin"
)
// Graph ...
type Graph struct {
v, e int
adj []*Bag
}
// NewGraph ...
func NewGraph(in *stdin.In) *Graph {
v := in.ReadInt()
adj := make([]*Bag, v)
for i := 0; i < v; i++ {
adj[i] = NewBag()
}
g := &Graph{v: v, e: 0, adj: adj}
e := in.ReadInt()
for i := 0; i < e; i++ {
v, w := in.ReadInt(), in.ReadInt()
g.AddEdge(v, w)
}
return g
}
// NewGraphV ...
func NewGraphV(v int) *Graph {
adj := make([]*Bag, v)
for i := 0; i < v; i++ {
adj[i] = NewBag()
}
return &Graph{v: v, e: 0, adj: adj}
}
// V ...
func (g *Graph) V() int {
return g.v
}
// E ...
func (g *Graph) E() int {
return g.e
}
// AddEdge ...
func (g *Graph) AddEdge(v, w int) {
g.adj[v].Add(w)
g.adj[w].Add(v)
g.e++
}
// Adj ...
func (g *Graph) Adj(v int) []int {
return g.adj[v].IntSlice()
}
func (g *Graph) 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 _, w := range g.Adj(i) {
adjs = adjs + fmt.Sprintf(" %d", w)
}
s += fmt.Sprintf("%d: %s\n", i, adjs)
}
return s
}