-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
130 lines (98 loc) · 2.07 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
package main
import (
"fmt"
"github.com/devkvlt/aoc"
)
type Map [][]byte
type Pos struct{ x, y int }
func (m Map) isValid(p Pos) bool {
return p.x >= 0 && p.y >= 0 && p.x < len(m) && p.y < len(m[0])
}
type Area map[Pos]struct{}
func (a Area) add(p Pos) {
a[p] = struct{}{}
}
func (m Map) options(p Pos) Area {
opts := make(Area)
dirs := []Pos{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
for _, dir := range dirs {
o := Pos{p.x + dir.x, p.y + dir.y}
if m.isValid(o) && int(m[o.x][o.y])-int(m[p.x][p.y]) <= 1 {
opts.add(o)
}
}
return opts
}
func parse(lines []string) (Map, Pos, Pos, []Pos) {
m := make(Map, len(lines))
var start Pos
var end Pos
lowest := []Pos{}
for i := 0; i < len(lines); i++ {
m[i] = make([]byte, len(lines[0]))
for j := 0; j < len(lines[0]); j++ {
m[i][j] = lines[i][j]
switch lines[i][j] {
case 'S':
start = Pos{i, j}
m[i][j] = 'a'
lowest = append(lowest, Pos{i, j})
case 'E':
end = Pos{i, j}
m[i][j] = 'z'
case 'a':
lowest = append(lowest, Pos{i, j})
}
}
}
return m, start, end, lowest
}
// https://en.wikipedia.org/wiki/Breadth-first_search
func trek(m Map, currentPos, targetPos Pos) int {
if currentPos == targetPos {
return 0
}
queue := []Pos{currentPos}
visited := make(Area)
visited.add(currentPos)
steps := 0
for len(queue) > 0 {
steps++
size := len(queue)
for i := 0; i < size; i++ {
curr := queue[0]
queue = queue[1:]
opts := m.options(curr)
for next := range opts {
if _, ok := visited[next]; !ok {
if next == targetPos {
return steps
}
queue = append(queue, next)
visited.add(next)
}
}
}
}
return -1
}
func part1(lines []string) {
m, start, end, _ := parse(lines)
fmt.Println(trek(m, start, end))
}
func part2(lines []string) {
m, _, end, lowest := parse(lines)
best := trek(m, lowest[0], end)
for i := 1; i < len(lowest); i++ {
s := trek(m, lowest[i], end)
if s < best && s != -1 {
best = s
}
}
fmt.Println(best)
}
func main() {
lines := aoc.Lines("input")
part1(lines) // 423
part2(lines) // 416
}