Dijkstra Shortest Path With Min Heap (Go)
Compute single source shortest paths in a weighted Go graph using Dijkstra with container heap.
Code
package main
import (
"container/heap"
"math"
)
type item struct { node string; dist int }
type pq []*item
func (p pq) Len() int { return len(p) }
func (p pq) Less(i, j int) bool { return p[i].dist < p[j].dist }
func (p pq) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p *pq) Push(x interface{}) { *p = append(*p, x.(*item)) }
func (p *pq) Pop() interface{} { old := *p; n := len(old); x := old[n-1]; *p = old[:n-1]; return x }
func dijkstra(graph map[string]map[string]int, start string) map[string]int {
dist := map[string]int{}
for n := range graph { dist[n] = math.MaxInt32 }
dist[start] = 0
h := &pq{{node: start, dist: 0}}
for h.Len() > 0 {
it := heap.Pop(h).(*item)
if it.dist > dist[it.node] { continue }
for neighbor, weight := range graph[it.node] {
nd := it.dist + weight
if nd < dist[neighbor] { dist[neighbor] = nd; heap.Push(h, &item{node: neighbor, dist: nd}) }
}
}
return dist
}Report a problem with this exampleOpens a pre-filled issue on GitHub.