Dijkstra's algorithm is a graph traversal algorithm that is used to find the shortest path between nodes in a weighted graph. It is often used to find the shortest route between two points in a network, such as a road map or a computer network.
The algorithm works by starting at the source node and visiting each neighbor in turn, updating the distance to each neighbor as it goes. It keeps track of the shortest distance to each node that it has visited, as well as the path that it took to get there. When it has visited all of the nodes, it returns the shortest path to the destination node.
Here is an example of Dijkstra's algorithm implemented in Golang:
code
package main
import (
"fmt"
)
// A graph is represented as an adjacency list
type Graph [][]int
// A node is represented as an integer
type Node int
// A path is represented as a slice of nodes
type Path []Node
// The distance between two nodes is represented as an integer
type Distance int
// The dijkstra function implements Dijkstra's algorithm to find the shortest
// path between two nodes in a graph.
func dijkstra(graph Graph, src, dst Node) (Path, Distance) {
// Initialize the distance and predecessor for each node
dist := make(map[Node]Distance)
pred := make(map[Node]Node)
for _, n := range []Node{Node(0), Node(1), Node(2)} {
dist[n] = -1
pred[n] = Node(-1)
}
// Set the distance for the source node to 0
dist[src] = 0
// Find the shortest path to each node
for len(dist) > 0 {
// Find the node with the smallest distance
minDist := -1
minNode := Node(-1)
for n, d := range dist {
if minDist == -1 || d < minDist {
minDist = d
minNode = n
}
}
// Update the distance for each neighbor
for _, neighbor := range graph[minNode] {
alt := dist[minNode] + 1
if alt < dist[neighbor] {
dist[neighbor] = alt
pred[neighbor] = minNode
}
}
// Remove the node from the map
delete(dist, minNode)
delete(pred, minNode)
}
// Reconstruct the path
path, node := []Node{}, dst
for node != Node(-1) {
path = append(path, node)
node = pred[node]
}
reverse(path)
return path, dist[dst]
}
// The reverse function reverses a slice of nodes
func reverse(slice []Node) {
for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
slice[i], slice[j] = slice[j], slice[i]
}
}
func main() {
// Create a sample graph
graph