use already calculated one.LowestCost

This commit is contained in:
onyx-and-iris 2024-12-19 02:44:26 +00:00
parent 17f2bc8223
commit f1cac7da7b
2 changed files with 9 additions and 9 deletions

View File

@ -4,6 +4,8 @@ import (
"bytes" "bytes"
) )
var LowestCost int
func Solve(buf []byte) (int, error) { func Solve(buf []byte) (int, error) {
r := bytes.NewReader(buf) r := bytes.NewReader(buf)
graph, err := parseLines(r) graph, err := parseLines(r)
@ -11,10 +13,10 @@ func Solve(buf []byte) (int, error) {
return 0, err return 0, err
} }
lowestCost, err := graph.dijkstra() LowestCost, err = graph.dijkstra()
if err != nil { if err != nil {
return 0, err return 0, err
} }
return lowestCost, nil return LowestCost, nil
} }

View File

@ -2,10 +2,10 @@ package two
import ( import (
hp "container/heap" hp "container/heap"
"math"
"slices" "slices"
"strings" "strings"
"github.com/onyx-and-iris/aoc2024/day-16/internal/one"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -32,20 +32,18 @@ func (g *graph) dijkstra() int {
hp.Push(heap, move{g.start, 0, []node{g.start}}) hp.Push(heap, move{g.start, 0, []node{g.start}})
visited := make(map[node]int) visited := make(map[node]int)
const turnCost int = 1000 const turnCost int = 1000
lowestCost := math.MaxInt
bestPaths := [][]node{} lowestCostPaths := [][]node{}
for heap.Len() > 0 { for heap.Len() > 0 {
current := hp.Pop(heap).(move) current := hp.Pop(heap).(move)
// we're on a path that's already exceeded the lowest cost // we're on a path that's already exceeded the lowest cost
if current.cost > lowestCost { if current.cost > one.LowestCost {
continue continue
} }
if g.valueAt(current.node) == 'E' { if g.valueAt(current.node) == 'E' {
bestPaths = append(bestPaths, current.path) lowestCostPaths = append(lowestCostPaths, current.path)
lowestCost = current.cost
continue continue
} }
@ -71,7 +69,7 @@ func (g *graph) dijkstra() int {
} }
possibleSafe := make(map[coords]struct{}) possibleSafe := make(map[coords]struct{})
for _, path := range bestPaths { for _, path := range lowestCostPaths {
for _, n := range path { for _, n := range path {
possibleSafe[n.coords] = struct{}{} possibleSafe[n.coords] = struct{}{}
} }