-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
134 lines (105 loc) · 2.04 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"fmt"
"github.com/danvolchek/AdventOfCode/lib"
)
type node struct {
x, y int
adjacent []*node
}
func (n *node) Id() string {
return fmt.Sprintf("%d,%d", n.y, n.x)
}
func (n *node) Adjacent() []*node {
return n.adjacent
}
func (n *node) String() string {
return n.Id()
}
func parse(char byte) int {
if char == 'S' {
return 9999999
}
if char == 'E' {
return -2
}
return int(char - 'a')
}
func solve(grid [][]int) int {
var starts []*node
var end string
gridMap := make(map[int]map[int]*node)
for y, line := range grid {
for x, height := range line {
n := &node{
x: x,
y: y,
adjacent: nil,
}
if height == 9999999 {
starts = append(starts, n)
}
if height == -2 {
end = n.Id()
}
if height == 0 {
starts = append(starts, n)
}
if gridMap[y] == nil {
gridMap[y] = make(map[int]*node)
}
gridMap[y][x] = n
if height == -2 {
grid[y][x] = parse('z')
}
if height == 9999999 {
grid[y][x] = parse('a')
}
}
}
for y, line := range grid {
for x, height := range line {
for iy := -1; iy <= 1; iy += 1 {
for ix := -1; ix <= 1; ix += 1 {
if iy == 0 && ix == 0 {
continue
}
if lib.Abs(iy)+lib.Abs(ix) == 2 {
continue
}
ey := y + iy
ex := x + ix
if ey < 0 || ex < 0 || ey >= len(grid) || ex >= len(grid[ey]) {
continue
}
if height >= grid[ey][ex]-1 {
gridMap[y][x].adjacent = append(gridMap[y][x].adjacent, gridMap[ey][ex])
}
}
}
}
}
distances := lib.Map(starts, func(s *node) (ret int) {
defer func() {
if r := recover(); r != nil {
ret = 9999999999999999
}
}()
result, ok := lib.BFS(s, func(n *node) bool {
return n.Id() == end
})
if !ok {
panic("not found")
}
return len(result) - 1
})
return lib.MinSlice(distances)
}
func main() {
solver := lib.Solver[[][]int, int]{
ParseF: lib.ParseGrid(parse),
SolveF: solve,
}
solver.Expect("Sabqponm\nabcryxxl\naccszExk\nacctuvwj\nabdefghi", 29)
solver.Verify(321)
}