package main import ( "container/heap" "fmt" "math" ) // Edge is a directed, non-negative weighted edge. type Edge struct { To int Weight int64 } // Dijkstra returns distances and predecessors from source. // Unreachable vertices have distance math.MaxInt64 and predecessor -1. func Dijkstra(graph [][]Edge, source int) ([]int64, []int, error) { if source < 0 || source >= len(graph) { return nil, nil, fmt.Errorf("source %d is out of range", source) } dist := make([]int64, len(graph)) prev := make([]int, len(graph)) for i := range graph { dist[i] = math.MaxInt64 prev[i] = -1 } dist[source] = 0 pq := &priorityQueue{{vertex: source, distance: 0}} heap.Init(pq) for pq.Len() > 0 { current := heap.Pop(pq).(item) if current.distance != dist[current.vertex] { continue // Ignore stale queue entries. } for _, edge := range graph[current.vertex] { if edge.To < 0 || edge.To >= len(graph) { return nil, nil, fmt.Errorf("edge destination %d is out of range", edge.To) } if edge.Weight < 0 { return nil, nil, fmt.Errorf("negative edge weight: %d", edge.Weight) } if current.distance > math.MaxInt64-edge.Weight { continue // The candidate distance would overflow. } candidate := current.distance + edge.Weight if candidate < dist[edge.To] { dist[edge.To] = candidate prev[edge.To] = current.vertex heap.Push(pq, item{vertex: edge.To, distance: candidate}) } } } return dist, prev, nil } type item struct { vertex int distance int64 } type priorityQueue []item func (pq priorityQueue) Len() int { return len(pq) } func (pq priorityQueue) Less(i, j int) bool { return pq[i].distance < pq[j].distance } func (pq priorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pq *priorityQueue) Push(value any) { *pq = append(*pq, value.(item)) } func (pq *priorityQueue) Pop() any { old := *pq last := old[len(old)-1] *pq = old[:len(old)-1] return last } // Lightweight tests keep this example self-contained in one source file. func main() { graph := [][]Edge{ {{To: 1, Weight: 4}, {To: 2, Weight: 1}}, {{To: 3, Weight: 1}}, {{To: 1, Weight: 2}, {To: 3, Weight: 5}}, nil, nil, } dist, prev, err := Dijkstra(graph, 0) if err != nil { panic(err) } assertEqual(dist, []int64{0, 3, 1, 4, math.MaxInt64}) assertEqual(prev, []int{-1, 2, 0, 1, -1}) _, _, err = Dijkstra([][]Edge{{{To: 0, Weight: -1}}}, 0) if err == nil { panic("expected negative-weight error") } } func assertEqual[T comparable](got, want []T) { if len(got) != len(want) { panic(fmt.Sprintf("length mismatch: got %d, want %d", len(got), len(want))) } for i := range got { if got[i] != want[i] { panic(fmt.Sprintf("index %d: got %v, want %v", i, got[i], want[i])) } } }