awesome-go/impl/algorithms/greedy_algorithms/dijkstra.go

73 lines
1.2 KiB
Go
Raw Normal View History

2024-01-20 08:55:19 +00:00
package main
import (
2024-01-20 08:55:19 +00:00
"fmt"
"math"
)
const V = 9
func minDistance(dist []int, sptSet []bool) int {
2024-01-20 08:55:19 +00:00
min := math.MaxInt32
var minIndex int
2024-01-20 08:55:19 +00:00
for v := 0; v < V; v++ {
if sptSet[v] == false && dist[v] <= min {
min = dist[v]
minIndex = v
}
}
2024-01-20 08:55:19 +00:00
return minIndex
}
func printSolution(dist []int) {
2024-01-20 08:55:19 +00:00
fmt.Println("Vertex \t Distance from Source")
for i := 0; i < V; i++ {
fmt.Printf("%d \t\t\t\t %d\n", i, dist[i])
}
}
func dijkstra(graph [V][V]int, src int) {
2024-01-20 08:55:19 +00:00
dist := make([]int, V)
sptSet := make([]bool, V)
2024-01-20 08:55:19 +00:00
for i := 0; i < V; i++ {
dist[i] = math.MaxInt32
sptSet[i] = false
}
2024-01-20 08:55:19 +00:00
dist[src] = 0
2024-01-20 08:55:19 +00:00
for count := 0; count < V-1; count++ {
u := minDistance(dist, sptSet)
2024-01-20 08:55:19 +00:00
sptSet[u] = true
2024-01-20 08:55:19 +00:00
for v := 0; v < V; v++ {
if !sptSet[v] && graph[u][v] != 0 && dist[u] != math.MaxInt32 && dist[u]+graph[u][v] < dist[v] {
dist[v] = dist[u] + graph[u][v]
}
}
}
2024-01-20 08:55:19 +00:00
printSolution(dist)
}
func main() {
2024-01-20 08:55:19 +00:00
graph := [V][V]int{
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0},
}
src := 0
dijkstra(graph, src)
}