Debian Codegraph @

build/grid.go

raw symbols SCIP
1 package build
2
3 import "strconv"
4
5 // Grid returns a virtual graph whose vertices correspond to integer
6 // points in the plane: y-coordinates being in the range 0..m-1,
7 // and x-coordinates in the range 0..n-1. Two vertices of a grid
8 // are adjacent whenever the corresponding points are at distance 1.
9 //
10 // Point (x, y) gets index nx + y, and index i corresponds to the point (i/n, i%n).
11 func Grid(m, n int) *Virtual {
12 switch {
13 case m < 0 || n < 0:
14 return nil
15 case m == 0 || n == 0:
16 return null
17 case m == 1 && n == 1:
18 return singleton()
19 case m == 1 && n == 2 || m == 2 && n == 1:
20 return edge()
21 case m == 1 && n > 2:
22 return line(n)
23 case m > 2 && n == 1:
24 return line(m)
25 case m*n/m != n:
26 panic("too large m=" + strconv.Itoa(m) + " n=" + strconv.Itoa(n))
27 }
28
29 g := generic0(m*n, func(v, w int) (edge bool) {
30 xdiff, ydiff := v/n-w/n, v%n-w%n
31 switch {
32 case xdiff == 0:
33 return ydiff == -1 || ydiff == 1
34 case ydiff == 0:
35 return xdiff == -1 || xdiff == 1
36 }
37 return
38 })
39
40 g.degree = func(v int) (deg int) {
41 vn := v % n
42 if v >= n { // up
43 deg++
44 }
45 if vn != 0 { // left
46 deg++
47 }
48 if vn != n-1 { // right
49 deg++
50 }
51 if v < g.order-n { // down
52 deg++
53 }
54 return
55 }
56
57 g.visit = func(v int, a int, do func(w int, c int64) bool) (aborted bool) {
58 if v < a-n {
59 return
60 }
61 if w := v - n; w >= a && do(w, 0) { // up
62 return true
63 }
64 vn := v % n
65 if vn != 0 { // left
66 if w := v - 1; w >= a && do(w, 0) {
67 return true
68 }
69 }
70 if vn != n-1 { // right
71 if w := v + 1; w >= a && do(w, g.cost(v, w)) {
72 return true
73 }
74 }
75 if v < g.order-n { // down
76 return do(v+n, 0)
77 }
78 return
79 }
80 return g
81 }