forked from shellfly/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigraph.go
88 lines (76 loc) · 1.37 KB
/
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
86
87
88
package algs4
import (
"fmt"
"github.com/shellfly/algo/stdin"
)
// DigraphInterface ...
type DigraphInterface interface {
V() int
Adj() []*DirectedEdge
}
// Digraph ...
type Digraph struct {
v, e int
adj []*Bag
}
// NewDigraph ...
func NewDigraph(in *stdin.In) *Digraph {
v := in.ReadInt()
adj := make([]*Bag, v)
for i := 0; i < v; i++ {
adj[i] = NewBag()
}
g := &Digraph{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
}
// NewDigraphV ...
func NewDigraphV(v int) *Digraph {
adj := make([]*Bag, v)
for i := 0; i < v; i++ {
adj[i] = NewBag()
}
return &Digraph{v: v, e: 0, adj: adj}
}
// V ...
func (g *Digraph) V() int {
return g.v
}
// E ...
func (g *Digraph) E() int {
return g.e
}
// AddEdge ...
func (g *Digraph) AddEdge(v, w int) {
g.adj[v].Add(w)
g.e++
}
// Adj ...
func (g *Digraph) Adj(v int) []int {
return g.adj[v].IntSlice()
}
// Reverse ...
func (g *Digraph) Reverse() *Digraph {
r := NewDigraphV(g.v)
for v := 0; v < g.v; v++ {
for _, w := range g.Adj(v) {
r.AddEdge(w, v)
}
}
return r
}
func (g *Digraph) 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
}