Dijkstra Shortest Path With Min Heap (Go)

Compute single source shortest paths in a weighted Go graph using Dijkstra with container heap.

GoData Fetching

Code

gosnippet
30 lines
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
}

How it works

Dijkstra Shortest Path With Min Heap (Go) is built around the functions Len, Less, Swap and Push.

Repetition is confined to for n := range graph { dist[n] = math.MaxInt32 } — the rest of the file is straight-line.

What to watch for

  • Nothing to vet in a supply-chain review — the file pulls in no packages.

Applying it

Entry signature: func (p pq) Len() int

Len is reached through its receiver type pq — call it on a value of that type rather than importing the name.

Statements that matter

func (p *pq) Pop() interface{} { old := *p; n := len(old); x := old[n-1]; *p = old[:n-1]; return x }
func (p pq) Less(i, j int) bool { return p[i].dist < p[j].dist }
func (p *pq) Push(x interface{}) { *p = append(*p, x.(*item)) }

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `container/heap`, `math`. The file defines `Len`, `Less`, `Swap` at load time.