Debian Codegraph @

graph.go

raw symbols SCIP
1 // Package graph contains generic implementations of basic graph algorithms.
2 //
3 // Generic graph algorithms
4 //
5 // The algorithms in this library can be applied to any graph data
6 // structure implementing the two Iterator methods: Order, which returns
7 // the number of vertices, and Visit, which iterates over the neighbors
8 // of a vertex.
9 //
10 // All algorithms operate on directed graphs with a fixed number
11 // of vertices, labeled from 0 to n-1, and edges with integer cost.
12 // An undirected edge {v, w} of cost c is represented by the two
13 // directed edges (v, w) and (w, v), both of cost c.
14 // A self-loop, an edge connecting a vertex to itself,
15 // is both directed and undirected.
16 //
17 // Graph data structures
18 //
19 // The type Mutable represents a directed graph with a fixed number
20 // of vertices and weighted edges that can be added or removed.
21 // The implementation uses hash maps to associate each vertex
22 // in the graph with its adjacent vertices. This gives constant
23 // time performance for all basic operations.
24 //
25 // The type Immutable is a compact representation of an immutable graph.
26 // The implementation uses lists to associate each vertex in the graph
27 // with its adjacent vertices. This makes for fast and predictable
28 // iteration: the Visit method produces its elements by reading
29 // from a fixed sorted precomputed list. This type supports multigraphs.
30 //
31 // Virtual graphs
32 //
33 // The subpackage graph/build offers a tool for building virtual graphs.
34 // In a virtual graph no vertices or edges are stored in memory,
35 // they are instead computed as needed. New virtual graphs are constructed
36 // by composing and filtering a set of standard graphs, or by writing
37 // functions that describe the edges of a graph.
38 //
39 // Tutorial
40 //
41 // The Basics example shows how to build a plain graph and how to
42 // efficiently use the Visit iterator, the key abstraction of this package.
43 //
44 // The DFS example contains a full implementation of depth-first search.
45 //
46 package graph
47
48 import (
49 "sort"
50 "strconv"
51 )
52
53 // Iterator describes a weighted graph; an Iterator can be used
54 // to describe both ordinary graphs and multigraphs.
55 type Iterator interface {
56 // Order returns the number of vertices in a graph.
57 Order() int
58
59 // Visit calls the do function for each neighbor w of vertex v,
60 // with c equal to the cost of the edge from v to w.
61 //
62 // • If do returns true, Visit returns immediately, skipping
63 // any remaining neighbors, and returns true.
64 //
65 // • The calls to the do function may occur in any order,
66 // and the order may vary.
67 //
68 Visit(v int, do func(w int, c int64) (skip bool)) (aborted bool)
69 }
70
71 // The maximum and minum value of an edge cost.
72 const (
73 Max int64 = 1<<63 - 1
74 Min int64 = -1 << 63
75 )
76
77 type edge struct {
78 v, w int
79 c int64
80 }
81
82 // String returns a description of g with two elements:
83 // the number of vertices, followed by a sorted list of all edges.
84 func String(g Iterator) string {
85 n := g.Order()
86 // This may be a multigraph, so we look for duplicates by counting.
87 count := make(map[edge]int)
88 for v := 0; v < n; v++ {
89 g.Visit(v, func(w int, c int64) (skip bool) {
90 count[edge{v, w, c}]++
91 return
92 })
93 }
94 edges := make([]edge, 0, len(count))
95 for e := range count {
96 edges = append(edges, e)
97 }
98 // Sort lexicographically on (v, w, c).
99 sort.Slice(edges, func(i, j int) bool {
100 v := edges[i].v == edges[j].v
101 w := edges[i].w == edges[j].w
102 switch {
103 case v && w:
104 return edges[i].c < edges[j].c
105 case v:
106 return edges[i].w < edges[j].w
107 default:
108 return edges[i].v < edges[j].v
109 }
110 })
111 // Build the string.
112 var buf []byte
113 buf = strconv.AppendInt(buf, int64(n), 10)
114 buf = append(buf, " ["...)
115 for _, e := range edges {
116 c := count[e]
117 if e.v < e.w {
118 // Collect edges in opposite directions into an undirected edge.
119 back := edge{e.w, e.v, e.c}
120 m := min(c, count[back])
121 count[back] -= m
122 buf = appendEdge(buf, e, m, true)
123 buf = appendEdge(buf, e, c-m, false)
124 } else {
125 buf = appendEdge(buf, e, c, false)
126 }
127 }
128 if len(edges) > 0 {
129 buf = buf[:len(buf)-1] // Remove trailing ' '.
130 }
131 buf = append(buf, ']')
132 return string(buf)
133 }
134
135 func appendEdge(buf []byte, e edge, count int, bi bool) []byte {
136 if count <= 0 {
137 return buf
138 }
139 if count > 1 {
140 buf = strconv.AppendInt(buf, int64(count), 10)
141 buf = append(buf, "×"...)
142 }
143 if bi {
144 buf = append(buf, '{')
145 } else {
146 buf = append(buf, '(')
147 }
148 buf = strconv.AppendInt(buf, int64(e.v), 10)
149 buf = append(buf, ' ')
150 buf = strconv.AppendInt(buf, int64(e.w), 10)
151 if bi {
152 buf = append(buf, '}')
153 } else {
154 buf = append(buf, ')')
155 }
156 if e.c != 0 {
157 buf = append(buf, ':')
158 switch e.c {
159 case Max:
160 buf = append(buf, "max"...)
161 case Min:
162 buf = append(buf, "min"...)
163 default:
164 buf = strconv.AppendInt(buf, e.c, 10)
165 }
166 }
167 buf = append(buf, ' ')
168 return buf
169 }
170
171 // Stats holds basic data about an Iterator.
172 type Stats struct {
173 Size int // Number of unique edges.
174 Multi int // Number of duplicate edges.
175 Weighted int // Number of edges with non-zero cost.
176 Loops int // Number of self-loops.
177 Isolated int // Number of vertices with outdegree zero.
178 }
179
180 // Check collects data about an Iterator.
181 func Check(g Iterator) Stats {
182 if g, ok := g.(*Immutable); ok {
183 return g.stats
184 }
185 _, mutable := g.(*Mutable)
186
187 n := g.Order()
188 degree := make([]int, n)
189 type edge struct{ v, w int }
190 edges := make(map[edge]bool)
191 var stats Stats
192 for v := 0; v < n; v++ {
193 g.Visit(v, func(w int, c int64) (skip bool) {
194 if w < 0 || w >= n {
195 panic("vertex out of range: " + strconv.Itoa(w))
196 }
197 if v == w {
198 stats.Loops++
199 }
200 if c != 0 {
201 stats.Weighted++
202 }
203 degree[v]++
204 if mutable { // A Mutable is never a multigraph.
205 stats.Size++
206 return
207 }
208 if edges[edge{v, w}] {
209 stats.Multi++
210 } else {
211 stats.Size++
212 }
213 edges[edge{v, w}] = true
214 return
215 })
216 }
217 for _, deg := range degree {
218 if deg == 0 {
219 stats.Isolated++
220 }
221 }
222 return stats
223 }
224
225 // Equal tells if g and h have the same number of vertices,
226 // and the same edges with the same costs.
227 func Equal(g, h Iterator) bool {
228 if g.Order() != h.Order() {
229 return false
230 }
231 edges := make(map[edge]int)
232 for v := 0; v < g.Order(); v++ {
233 g.Visit(v, func(w int, c int64) (skip bool) {
234 edges[edge{v, w, c}]++
235 return
236 })
237 if h.Visit(v, func(w int, c int64) (skip bool) {
238 if edges[edge{v, w, c}] == 0 {
239 return true
240 }
241 edges[edge{v, w, c}]--
242 return
243 }) {
244 return false
245 }
246 for _, n := range edges {
247 if n > 0 {
248 return false
249 }
250 }
251 }
252 return true
253 }
254
255 func min(x, y int) int {
256 if x < y {
257 return x
258 }
259 return y
260 }