-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
96 lines (84 loc) · 1.72 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
package main
import (
"io"
aoc "github.com/teivah/advent-of-code"
)
func fs(input io.Reader, minStraight, maxStraight int) int {
board := aoc.ParseBoard[int](aoc.ReaderToStrings(input), aoc.RuneToInt)
return shortest(board, minStraight, maxStraight)
}
func shortest(board aoc.Board[int], minStraight, maxStraight int) int {
type state struct {
loc aoc.Location
straight int
}
type entry struct {
state
heatLoss int
}
target := aoc.NewPosition(board.Rows-1, board.Cols-1)
visited := make(map[state]int)
q := aoc.NewPriorityQueue[entry](func(a, b entry) int {
return a.heatLoss - b.heatLoss
})
q.Push(entry{
state: state{
loc: aoc.NewLocation(0, 1, aoc.Right),
straight: 1,
},
})
q.Push(entry{
state: state{
loc: aoc.NewLocation(1, 0, aoc.Down),
straight: 1,
},
})
for !q.IsEmpty() {
e := q.Pop()
pos := e.loc.Pos
if !pos.IsInside(board) {
continue
}
heat := board.Get(pos) + e.heatLoss
if pos == target {
if e.straight < minStraight {
continue
}
// Thanks to the priority queue, at this stage we already know this is the
// shortest path.
return heat
}
if v, exists := visited[e.state]; exists {
if v <= heat {
continue
}
}
visited[e.state] = heat
if e.straight >= minStraight {
q.Push(entry{
state: state{
loc: e.loc.Turn(aoc.Left, 1),
straight: 1,
},
heatLoss: heat,
})
q.Push(entry{
state: state{
loc: e.loc.Turn(aoc.Right, 1),
straight: 1,
},
heatLoss: heat,
})
}
if e.straight < maxStraight {
q.Push(entry{
state: state{
loc: e.loc.Straight(1),
straight: e.straight + 1,
},
heatLoss: heat,
})
}
}
panic("no result found")
}