-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
113 lines (99 loc) · 1.92 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
package main
import (
"io"
"github.com/teivah/go-aoc"
)
type Cell struct {
empty bool
obstruction bool
}
func fs1(input io.Reader) int {
var pos aoc.Position
dir := aoc.Up
board := aoc.NewBoardFromReader(input, func(row, col int, r rune) Cell {
switch r {
default:
panic(r)
case '.':
return Cell{empty: true}
case '#':
return Cell{obstruction: true}
case '^':
pos = aoc.NewPosition(row, col)
return Cell{empty: true}
}
})
visited := make(map[aoc.Position]struct{})
loc := aoc.NewLocation(pos.Row, pos.Col, dir)
for {
visited[loc.Pos] = struct{}{}
var stop bool
loc, stop = move(board, loc)
if stop {
break
}
}
return len(visited)
}
func move(board aoc.Board[Cell], loc aoc.Location) (aoc.Location, bool) {
next := loc.Move(loc.Dir, 1)
if !board.Contains(next.Pos) {
return aoc.Location{}, true
}
switch {
case board.Get(next.Pos).obstruction:
return move(board, loc.Turn(aoc.Right, 0))
case board.Get(next.Pos).empty:
return next, false
default:
panic(board.Get(next.Pos))
}
}
func fs2(input io.Reader) int {
var pos aoc.Position
dir := aoc.Up
board := aoc.NewBoardFromReader(input, func(row, col int, r rune) Cell {
switch r {
default:
panic(r)
case '.':
return Cell{empty: true}
case '#':
return Cell{obstruction: true}
case '^':
pos = aoc.NewPosition(row, col)
return Cell{empty: true}
}
})
res := 0
for cur, cell := range board.Positions {
switch {
case cell.obstruction:
continue
case cell.empty:
board.Positions[cur] = Cell{obstruction: true}
default:
panic(cell)
}
visited := make(map[aoc.Location]bool)
loc := aoc.NewLocation(pos.Row, pos.Col, dir)
loop := false
for {
if visited[loc] {
loop = true
break
}
visited[loc] = true
var stop bool
loc, stop = move(board, loc)
if stop {
break
}
}
if loop {
res++
}
board.Positions[cur] = Cell{empty: true}
}
return res
}