-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
131 lines (101 loc) · 2.14 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
package main
import (
"container/heap"
"fmt"
"github.com/devkvlt/aoc"
)
// https://pkg.go.dev/container/heap#example-package-PriorityQueue
type State struct {
heatloss int
pos Pos
dir Pos
straight int
}
type PQ []*State
func (pq PQ) Len() int {
return len(pq)
}
func (pq PQ) Less(i, j int) bool {
return pq[i].heatloss < pq[j].heatloss
}
func (pq PQ) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func (pq *PQ) Push(x any) {
*pq = append(*pq, x.(*State))
}
func (pq *PQ) Pop() any {
old := *pq
n := len(old)
state := old[n-1]
old[n-1] = nil // avoid memory leak
*pq = old[0 : n-1]
return state
}
var grid = aoc.Lines("input")
var (
height = len(grid)
width = len(grid[0])
)
type Pos struct{ x, y int }
var (
none = Pos{0, 0}
up = Pos{0, -1}
down = Pos{0, 1}
left = Pos{-1, 0}
right = Pos{1, 0}
)
func isValid(p Pos) bool {
return p.x >= 0 && p.x < width && p.y >= 0 && p.y < height
}
func advance(p, dir Pos) Pos {
return Pos{p.x + dir.x, p.y + dir.y}
}
func split(dir Pos) []Pos {
if dir == none {
return []Pos{right, down}
}
return []Pos{{dir.y, dir.x}, {-dir.y, -dir.x}}
}
type Key struct {
pos Pos
dir Pos
straight int
}
func solveWith(minStraight, maxStraight int) {
start := Pos{0, 0}
end := Pos{width - 1, height - 1}
seen := map[Key]bool{}
pq := PQ{}
heap.Push(&pq, &State{heatloss: 0, pos: start, dir: none, straight: 0})
for len(pq) > 0 {
s := heap.Pop(&pq).(*State)
if s.pos == end && s.straight >= minStraight {
fmt.Println(s.heatloss)
break
}
key := Key{s.pos, s.dir, s.straight}
if seen[key] {
continue
}
seen[key] = true
if s.straight < maxStraight && s.dir != none {
next := advance(s.pos, s.dir)
if isValid(next) {
heap.Push(&pq, &State{s.heatloss + int(grid[next.y][next.x]) - 48, next, s.dir, s.straight + 1})
}
}
if s.straight >= minStraight || s.dir == none {
for _, dir := range split(s.dir) {
next := advance(s.pos, dir)
if isValid(next) {
heap.Push(&pq, &State{s.heatloss + int(grid[next.y][next.x]) - 48, next, dir, 1})
}
}
}
}
}
func main() {
solveWith(1, 3) // 758
solveWith(4, 10) // 892
}