Anonymous user
Dijkstra's algorithm: Difference between revisions
→{{header|Go}}: use map size hints and pre-allocate slices; avoid named returns; gofmt; add playground link
(Added solution for Delphi.) |
(→{{header|Go}}: use map size hints and pre-allocate slices; avoid named returns; gofmt; add playground link) |
||
Line 1,869:
=={{header|Go}}==
<lang go>package main
import (
)
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue struct {
m map[Vertex]int // value to index
pr
pr map[Vertex]int▼
}
func (pq *PriorityQueue) Len() int { return len(pq.items) }
func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }
func (pq *PriorityQueue) Swap(i, j int) {
}
func (pq *PriorityQueue) Push(x interface{}) {
}
func (pq *PriorityQueue) Pop() interface{} {
}
// update modifies the priority of an item in the queue.
func (pq *PriorityQueue) update(item Vertex, priority int) {
}
func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {
}
const (
)
func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {
dist = make(map[Vertex]int)▼
prev = make(map[Vertex]Vertex, len(vs))
dist[sid] = 0
q := &PriorityQueue{
▲ for _, v := range g.Vertices() {
items: make([]Vertex, 0, len(vs)),
if v != sid {▼
dist[v] = Infinity▼
▲ }
prev[v] = Uninitialized▼
q.addWithPriority(v, dist[v])▼
for len(q.items) != 0 {▼
}
u := heap.Pop(q).(Vertex)▼
▲ for _, v := range g.Neighbors(u) {
alt := dist[u] + g.Weight(u, v)▼
▲ }
if alt < dist[v] {▼
dist[v] = alt▼
prev[v] = u▼
for _, v := range g.Neighbors(u) {
q.update(v, alt)▼
return dist, prev▼
}
}
▲ }
}
// A Graph is the interface implemented by graphs that
// this algorithm can run on.
type Graph interface {
}
// Nonnegative integer ID of vertex
type Vertex int
// sg is a graph of strings that satisfies the Graph interface.
type sg struct {
}
func newsg(ids map[string]Vertex) sg {
}
func (g sg) edge(u, v string, w int) {
}
func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {
}
func (g sg) Vertices()
vs :=
for _, v := range g.ids {
▲ }
}
func (g sg) Neighbors(u Vertex)
for v := range g.edges[u] {
▲ }
}
func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }
func main() {
}</lang>
Runable on the [https://play.golang.org/p/w6nJ1ovjwn7 Go playground].
{{out}}
<pre>
|