-
Notifications
You must be signed in to change notification settings - Fork 5
/
graph.go
73 lines (59 loc) · 1.58 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
73
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package graph provides interfaces and basic representations for
// graphs.
//
// Sub-packages provide common graph algorithms.
package graph
// Graph represents a directed graph. The nodes of the graph must be
// densely numbered starting at 0.
type Graph interface {
// NumNodes returns the number of nodes in this graph.
NumNodes() int
// Out returns the nodes to which node i points.
Out(i int) []int
}
// BiGraph extends Graph to graphs that represent both out-edges and
// in-edges.
type BiGraph interface {
Graph
// In returns the nodes which point to node i.
In(i int) []int
}
// MakeBiGraph constructs a BiGraph from what may be a unidirectional
// Graph. If g is already a BiGraph, this returns g.
func MakeBiGraph(g Graph) BiGraph {
if g, ok := g.(BiGraph); ok {
return g
}
preds := make([][]int, g.NumNodes())
for i := range preds {
for _, j := range g.Out(i) {
preds[j] = append(preds[j], i)
}
}
return &bigraph{g, preds}
}
type bigraph struct {
Graph
preds [][]int
}
func (b *bigraph) In(i int) []int {
return b.preds[i]
}
// IntGraph is a basic Graph g where g[i] is the list of out-edge
// indexes of node i.
type IntGraph [][]int
func (g IntGraph) NumNodes() int {
return len(g)
}
func (g IntGraph) Out(i int) []int {
return g[i]
}
// Edge identifies an edge in a graph. Given Graph g, Edge e
// represents edge g.Out(e.Node)[e.Edge].
type Edge struct {
Node int // Node ID
Edge int // Edge index
}