aoc2024/day-10/internal/one/solve.go

69 lines
1.2 KiB
Go
Raw Normal View History

2024-12-10 21:45:16 +00:00
package one
import (
"bytes"
log "github.com/sirupsen/logrus"
"github.com/onyx-and-iris/aoc2024/day-10/internal/queue"
)
const target = '9'
func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf)
graph, err := parseLines(r)
if err != nil {
return 0, err
}
var totalScore int
queue := queue.New[point]()
for _, pos := range graph.startPositions {
if graph.isOutOfBounds(pos) {
continue
}
queue.Enqueue(pos)
var score int
visited := make(map[point]struct{})
endpoints := make(map[point]struct{})
for !queue.IsEmpty() {
current := queue.Dequeue()
_, ok := endpoints[current]
if ok {
continue
}
endpoints[current] = struct{}{}
if graph.valueAt(current) == target {
score++
continue
}
_, ok = visited[current]
if ok {
continue
}
visited[current] = struct{}{}
for _, n := range neighbours(current) {
if graph.isOutOfBounds(n) {
continue
}
if graph.valueAt(n)-graph.valueAt(current) == 1 {
log.Tracef("pushing %v with value %s back onto the queue\n", n, string(graph.valueAt(n)))
queue.Enqueue(n)
}
}
}
log.Debugf("score for trailhead %v - %d\n", pos, score)
totalScore += score
}
return totalScore, nil
}