Dijkstra with container/heap
BFS finds the fewest steps. When every edge has its own cost (minutes, metres, coins), the fewest steps is no longer the cheapest route: one long road can lose to a chain of short ones. Dijkstra's algorithm is BFS for weighted graphs, as long as no cost is negative.
Always the nearest unsettled node
BFS takes nodes in the order they were found. Dijkstra takes them in order of cost so far: it always continues from the cheapest node it hasn't finished with. When a node is taken out that way, no cheaper route to it can turn up later, because every other route would start from a node that's already at least as expensive.
For "always give me the cheapest" you need a priority queue. Go has one in container/heap: you write five small methods on a slice type, and heap.Push and heap.Pop keep the cheapest entry on top.
type queue []visit
func (q queue) Len() int { return len(q) }
func (q queue) Less(i, j int) bool { return q[i].minutes < q[j].minutes }
func (q queue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
func (q *queue) Push(x any) { *q = append(*q, x.(visit)) }
func (q *queue) Pop() any { /* remove and return the last element */ }
Call heap.Push(q, v) and heap.Pop(q), not q.Push and q.Pop: the package functions keep the order, and your methods are only the building blocks they use. heap.Pop returns any, so take the value back out with .(visit).
The loop
best := map[string]int{start: 0}
q := &queue{{start, 0}}
for q.Len() > 0 {
cur := heap.Pop(q).(visit)
if cur.minutes > best[cur.town] {
continue // a slower entry from before; this town was improved since
}
for _, e := range g[cur.town] {
m := cur.minutes + e.Minutes
if old, seen := best[e.To]; !seen || m < old {
best[e.To] = m
heap.Push(q, visit{e.To, m})
}
}
}
A town can be pushed several times, once for every improvement. Instead of removing old entries from the heap, the continue skips them when they come out. That's the simplest correct version, and the one most people write in puzzles.
Dijkstra costs about O(E log V) for E edges and V nodes. Grid puzzles with costs per cell work the same way: the nodes are cells, and the edges are moves to neighbours.
Task
This lesson's input lists roads between towns with how many minutes each takes. Roads go both ways. The queue type is ready.
- Complete
distances(g, start) map[string]int: the fewest minutes fromstartto every town it can reach. Towns it can't reach are not in the map. You'll need to importcontainer/heap. - Complete
shortest(g, start, goal) (int, bool): the fewest minutes fromstarttogoal, andfalsewhen there's no way there.