The Dijkstra algorithm is a popular algorithm used to find the shortest path between two vertices in a graph. It works by maintaining a priority queue of vertices and their tentative distances from the source vertex. The algorithm iteratively selects the vertex with the smallest tentative distance, updates the distances of its neighboring vertices, and continues until it has visited all vertices or reached the target vertex.
Here's an example implementation of the Dijkstra algorithm in Golang:
package main
import (
"fmt"
"math"
)
type Edge struct {
src, dest, weight int
}
type Graph struct {
vertices []int
edges []Edge
}
func Dijkstra(graph Graph, src int, dest int) {
numVertices := len(graph.vertices)
distances := make([]int, numVertices)
visited := make([]bool, numVertices)
previous := make([]int, numVertices)
for i := 0; i < numVertices; i++ {
distances[i] = math.MaxInt32
visited[i] = false
previous[i] = -1
}
distances[src] = 0
for count := 0; count < numVertices-1; count++ {
u := minDistance(distances, visited)
visited[u] = true
for _, edge := range graph.edges {
if edge.src == u && !visited[edge.dest] && distances[u] != math.MaxInt32 && distances[u]+edge.weight < distances[edge.dest] {
distances[edge.dest] = distances[u] + edge.weight
previous[edge.dest] = u
}
}
}
printPath(dest, previous)
fmt.Printf("Shortest distance from vertex %d to vertex %d is %d\n", src, dest, distances[dest])
}
func minDistance(distances []int, visited []bool) int {
min := math.MaxInt32
minIndex := -1
for v := 0; v < len(distances); v++ {
if !visited[v] && distances[v] <= min {
min = distances[v]
minIndex = v
}
}
return minIndex
}
func printPath(dest int, previous []int) {
if previous[dest] != -1 {
printPath(previous[dest], previous)
fmt.Printf("%d ", dest)
} else {
fmt.Printf("%d ", dest)
}
}
func main() {
vertices := []int{0, 1, 2, 3, 4, 5, 6}
edges := []Edge{
{0, 1, 4},
{0, 2, 1},
{1, 3, 1},
{2, 1, 2},
{2, 3, 5},
{3, 4, 3},
{4, 5, 2},
{5, 6, 3},
}
graph := Graph{vertices, edges}
src := 0
dest := 6
Dijkstra(graph, src, dest)
}
In this example, we create a Graph struct with an array of vertices and edges. We then define the Dijkstra function which takes the graph, source vertex, and destination vertex as parameters. Inside this function, we initialize the distances, visited, and previous arrays. We set the distance of the source vertex to 0 and iterate through all vertices to find the minimum distance vertex that has not been visited yet. We then update the distances of its neighboring vertices if a shorter path is found. Finally, we print the shortest path and the shortest distance from the source to the destination vertex.
In the main function, we create a sample graph with vertices and edges. We specify the source and destination vertices and call the Dijkstra function to find the shortest path and distance. The output will display the shortest path from the source to the destination and the shortest distance.