-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
119 lines (105 loc) · 1.91 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
package main
import (
"fmt"
"github.com/devkvlt/aoc"
)
var (
grid [][]byte
height int
width int
start Pos
visited []Pos
)
type Pos struct{ x, y int }
func init() {
lines := aoc.Lines("input")
height = len(lines)
width = len(lines[0])
grid = make([][]byte, height)
for y := 0; y < height; y++ {
grid[y] = make([]byte, width)
for x := 0; x < width; x++ {
grid[y][x] = lines[y][x]
ch := lines[y][x]
if ch == '^' {
start = Pos{x, y}
}
}
}
}
func valid(p Pos) bool {
return 0 <= p.x && p.x < width && 0 <= p.y && p.y < height
}
func next(p Pos, dir byte) Pos {
return map[byte]Pos{
'^': {p.x, p.y - 1},
'>': {p.x + 1, p.y},
'v': {p.x, p.y + 1},
'<': {p.x - 1, p.y},
}[dir]
}
func turn(dir byte) byte {
return map[byte]byte{'^': '>', '>': 'v', 'v': '<', '<': '^'}[dir]
}
func part1() {
curr := start
dir := grid[curr.y][curr.x]
seen := map[Pos]bool{curr: true}
for valid(curr) {
next := next(curr, dir)
if !valid(next) {
break
}
if grid[next.y][next.x] != '#' {
if !seen[next] {
visited = append(visited, next)
}
seen[next] = true
curr = next
} else {
dir = turn(dir)
}
}
fmt.Println(len(visited) + 1) // +1 to include initial pos
}
type PosDir struct {
pos Pos
dir byte
}
func loop(p Pos) int {
grid[p.y][p.x] = '#'
curr := start
dir := grid[curr.y][curr.x]
seen := map[PosDir]bool{{curr, dir}: true}
for valid(curr) {
next := next(curr, dir)
if !valid(next) {
break
}
if grid[next.y][next.x] == '#' {
dir = turn(dir)
continue
}
if seen[PosDir{next, dir}] {
grid[p.y][p.x] = '.'
return 1
}
seen[PosDir{next, dir}] = true
curr = next
}
grid[p.y][p.x] = '.'
return 0
}
func part2() {
sum := 0
for _, p := range visited {
sum += loop(p)
}
fmt.Println(sum)
}
// NOTE: part2 needs part1 to run first because it relies on visited which is
// calculated in part1.
func main() {
part1() // 4890
part2() // 1995
}