Created
July 11, 2022 18:06
-
-
Save zergon321/f8b370a099862574323b150775d39abf to your computer and use it in GitHub Desktop.
Dijkstra's algorithm in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/zergon321/arrayqueue" | |
) | |
type Node struct { | |
Cost int | |
Edges map[string]int | |
Traversed bool | |
Path []string | |
} | |
func main() { | |
graph := map[string]*Node{ | |
"1": &Node{ | |
Cost: -1, | |
Edges: map[string]int{ | |
"2": 7, | |
"3": 9, | |
"6": 14, | |
}, | |
}, | |
"2": &Node{ | |
Cost: -1, | |
Edges: map[string]int{ | |
"3": 10, | |
"4": 15, | |
}, | |
}, | |
"3": &Node{ | |
Cost: -1, | |
Edges: map[string]int{ | |
"4": 11, | |
"6": 2, | |
}, | |
}, | |
"4": &Node{ | |
Cost: -1, | |
Edges: map[string]int{ | |
"2": 15, | |
"3": 11, | |
"5": 6, | |
}, | |
}, | |
"5": &Node{ | |
Cost: -1, | |
Edges: map[string]int{ | |
"4": 6, | |
"6": 9, | |
}, | |
}, | |
"6": &Node{ | |
Cost: -1, | |
Edges: map[string]int{ | |
"1": 14, | |
"3": 2, | |
"5": 9, | |
}, | |
}, | |
} | |
queue, err := arrayqueue.NewQueue(len(graph)) | |
handleError(err) | |
graph["1"].Cost = 0 | |
graph["1"].Traversed = true | |
graph["1"].Path = []string{"1"} | |
queue.Enqueue(graph["1"]) | |
for queue.Length() > 0 { | |
value, err := queue.Dequeue() | |
handleError(err) | |
vertex := value.(*Node) | |
for neighbourName, edgeWeight := range vertex.Edges { | |
cost := vertex.Cost + edgeWeight | |
neighbour := graph[neighbourName] | |
if neighbour.Traversed { | |
continue | |
} | |
if neighbour.Cost == -1 || cost < neighbour.Cost { | |
pathLen := len(vertex.Path) + 1 | |
neighbour.Cost = cost | |
neighbour.Path = make( | |
[]string, len(vertex.Path)+1) | |
copy(neighbour.Path, vertex.Path) | |
neighbour.Path[pathLen-1] = neighbourName | |
} | |
queue.Enqueue(neighbour) | |
} | |
vertex.Traversed = true | |
} | |
fmt.Println(graph) | |
} | |
func handleError(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment