aoc2024/day-15/internal/two/solve.go

67 lines
1.2 KiB
Go
Raw Permalink Normal View History

2024-12-18 14:45:27 +00:00
package two
import (
"bytes"
log "github.com/sirupsen/logrus"
)
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
graph, dirs, err := parseLines(r)
if err != nil {
return 0, err
}
log.Debugf("\n%s\n", graph.String())
for _, dir := range dirs {
log.Debugf("about to explore '%s' direction from robot location (%s)", string(dir), graph.robot.String())
switch directions(dir) {
case N, S:
2025-01-07 17:33:55 +00:00
exploreNorthSouth(directions(dir), graph)
2024-12-18 14:45:27 +00:00
case W, E:
2025-01-07 17:33:55 +00:00
exploreWestEast(directions(dir), graph)
2024-12-18 14:45:27 +00:00
}
log.Debugf("\n%s\n", graph.String())
}
var sum int
for y, line := range graph.data {
for x, r := range line {
if r == '[' {
sum += (100 * y) + x
}
}
}
return sum, nil
}
2025-01-07 17:33:55 +00:00
func exploreWestEast(direction direction, g *graph) {
stack := newStack()
if ok := exploreDFS(g, g.robot, direction, stack); !ok {
2024-12-18 14:45:27 +00:00
log.Debug("path ends with '#', continuing...")
return
}
for !stack.IsEmpty() {
point := stack.Pop().(point)
2025-01-07 17:33:55 +00:00
g.updateBox(point, direction)
2024-12-18 14:45:27 +00:00
}
2025-01-07 17:33:55 +00:00
g.updateRobot(direction)
2024-12-18 14:45:27 +00:00
}
2025-01-07 17:33:55 +00:00
func exploreNorthSouth(direction direction, g *graph) {
om, ok := exploreBFS(g, direction)
2024-12-18 14:45:27 +00:00
if ok {
for pair := om.Newest(); pair != nil; pair = pair.Prev() {
2025-01-07 17:33:55 +00:00
g.updateBox(pair.Key, direction)
2024-12-18 14:45:27 +00:00
}
2025-01-07 17:33:55 +00:00
g.updateRobot(direction)
2024-12-18 14:45:27 +00:00
}
}