-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
132 lines (114 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
131
132
package main
import (
"io"
"math"
"github.com/teivah/go-aoc"
)
type cell uint32
const (
end cell = iota
empty
wall
)
func (c cell) isNonWall() bool {
return c == empty || c == end
}
func fs1(input io.Reader) int {
s := newSolver(input)
for !s.q.IsEmpty() {
s.step()
}
return s.best
}
func fs2(input io.Reader) int {
s := newSolver(input)
for !s.q.IsEmpty() {
s.step()
}
return len(s.paths)
}
type state struct {
loc aoc.Location
count int
path map[aoc.Position]bool
}
type solver struct {
q aoc.Heap[state]
board aoc.Board[cell]
visited map[aoc.Location]int
best int
paths map[aoc.Position]bool
}
func newSolver(input io.Reader) *solver {
var start aoc.Location
board := aoc.ParseBoard(aoc.ReaderToStrings(input), func(r rune, pos aoc.Position) cell {
switch r {
default:
panic(r)
case 'S':
start = aoc.NewLocation(pos.Row, pos.Col, aoc.Right)
return empty
case 'E':
return end
case '.':
return empty
case '#':
return wall
}
})
s := solver{
q: aoc.NewHeap(func(a, b state) bool {
return a.count < b.count
}),
board: board,
visited: make(map[aoc.Location]int),
best: math.MaxInt,
}
s.q.Push(state{
loc: start,
count: 0,
path: map[aoc.Position]bool{start.Pos: true},
})
return &s
}
func (s *solver) step() {
cur := s.q.Pop()
if s.board.Get(cur.loc.Pos) == end {
if cur.count < s.best {
s.best = cur.count
s.paths = cur.path
} else if cur.count == s.best {
for p := range cur.path {
s.paths[p] = true
}
}
return
}
if cur.count >= s.best {
return
}
if c, ok := s.visited[cur.loc]; ok && c < cur.count {
return
}
s.visited[cur.loc] = cur.count
next := cur.loc.Straight(1)
if s.board.Get(next.Pos).isNonWall() {
path := aoc.MapCopy(cur.path)
path[next.Pos] = true
s.q.Push(state{
loc: next,
count: cur.count + 1,
path: path,
})
}
s.q.Push(state{
loc: cur.loc.Turn(aoc.Left, 0),
count: cur.count + 1000,
path: cur.path,
})
s.q.Push(state{
loc: cur.loc.Turn(aoc.Right, 0),
count: cur.count + 1000,
path: cur.path,
})
}