-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgrid_walk.go
64 lines (53 loc) · 1005 Bytes
/
grid_walk.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
package main
import "fmt"
import "container/list"
type Vertex struct {
X int
Y int
}
const LIMIT = 19
func digit_sum(n int) int {
if n < 0 {
n = n * -1
}
sum := 0
d, r := 0, 0
for n > 0 {
d = n / 10
r = n % 10
sum += r
n -= r
if d > 0 {
n /= 10
}
}
return sum
}
func accessible(v Vertex) bool {
return digit_sum(v.X)+digit_sum(v.Y) <= LIMIT
}
func explore(visited map[Vertex]bool, queue *list.List, v Vertex) {
_, ok := visited[v]
if accessible(v) && !ok {
visited[v] = true
queue.PushBack(v)
}
}
func main() {
start := Vertex{0, 0}
visited := make(map[Vertex]bool)
queue := list.New()
visited[start] = true
queue.PushBack(start)
for queue.Len() > 0 {
next := queue.Front()
queue.Remove(next)
nv := next.Value.(Vertex)
x, y := nv.X, nv.Y
explore(visited, queue, Vertex{x - 1, y})
explore(visited, queue, Vertex{x + 1, y})
explore(visited, queue, Vertex{x, y - 1})
explore(visited, queue, Vertex{x, y + 1})
}
fmt.Println(len(visited))
}