MCPcopy Index your code
hub / github.com/TheAlgorithms/Go / Dijkstra

Method Dijkstra

graph/dijkstra.go:25–69  ·  view source on GitHub ↗
(start, end int)

Source from the content-addressed store, hash-verified

23}
24
25func (g *Graph) Dijkstra(start, end int) (int, bool) {
26 visited := make(map[int]bool)
27 nodes := make(map[int]*Item)
28
29 nodes[start] = &Item{
30 dist: 0,
31 node: start,
32 }
33 pq := sort.MaxHeap{}
34 pq.Init(nil)
35 pq.Push(*nodes[start])
36
37 visit := func(curr Item) {
38 visited[curr.node] = true
39 for n, d := range g.edges[curr.node] {
40 if visited[n] {
41 continue
42 }
43
44 item := nodes[n]
45 dist2 := curr.dist + d
46 if item == nil {
47 nodes[n] = &Item{node: n, dist: dist2}
48 pq.Push(*nodes[n])
49 } else if item.dist > dist2 {
50 item.dist = dist2
51 pq.Update(*item)
52 }
53 }
54 }
55
56 for pq.Size() > 0 {
57 curr := pq.Pop().(Item)
58 if curr.node == end {
59 break
60 }
61 visit(curr)
62 }
63
64 item := nodes[end]
65 if item == nil {
66 return -1, false
67 }
68 return item.dist, true
69}

Callers 1

TestDijkstraFunction · 0.95

Calls 5

InitMethod · 0.95
PushMethod · 0.95
UpdateMethod · 0.95
SizeMethod · 0.95
PopMethod · 0.95

Tested by 1

TestDijkstraFunction · 0.76