实现说明
活动部件是函数 Len、Less、Swap、Push。
在这里做循环的是 for n := range graph { dist[n] = math.MaxInt32 }。
使用要点
Len是公开入口,文件里其余部分都是为它服务的内部实现。
常见问题
安装包是准备工作的一部分吗?
不需要。只用内建 API,安装这一步可以省掉。 全部导入都来自标准库:container/heap、math。 文件在加载时定义 Len、Less、Swap。
主要签名是 func (p pq) Len() int
核心语句
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)) }
代码示例
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
}