Skip to content

Commit 8d5806a

Browse files
author
Abhinav kumar
authored
Create Diljstra.go
1 parent b5c88b3 commit 8d5806a

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

Graphs/Diljstra.go

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math"
6+
)
7+
8+
// Define a struct to represent a graph.
9+
type Graph struct {
10+
nodes map[string]map[string]float64
11+
}
12+
13+
// Add an edge to the graph.
14+
func (g *Graph) AddEdge(node1, node2 string, weight float64) {
15+
if g.nodes == nil {
16+
g.nodes = make(map[string]map[string]float64)
17+
}
18+
if g.nodes[node1] == nil {
19+
g.nodes[node1] = make(map[string]float64)
20+
}
21+
if g.nodes[node2] == nil {
22+
g.nodes[node2] = make(map[string]float64)
23+
}
24+
g.nodes[node1][node2] = weight
25+
g.nodes[node2][node1] = weight // Assuming an undirected graph
26+
}
27+
28+
// Dijkstra's algorithm to find the shortest path.
29+
func Dijkstra(graph Graph, startNode string) map[string]float64 {
30+
distances := make(map[string]float64)
31+
visited := make(map[string]bool)
32+
33+
for node := range graph.nodes {
34+
distances[node] = math.Inf(1)
35+
}
36+
37+
distances[startNode] = 0
38+
39+
for {
40+
var closestNode string
41+
var shortestDistance float64 = math.Inf(1)
42+
43+
for node, distance := range distances {
44+
if !visited[node] && distance < shortestDistance {
45+
closestNode = node
46+
shortestDistance = distance
47+
}
48+
}
49+
50+
if closestNode == "" {
51+
break
52+
}
53+
54+
visited[closestNode] = true
55+
56+
for neighbor, weight := range graph.nodes[closestNode] {
57+
if newDistance := distances[closestNode] + weight; newDistance < distances[neighbor] {
58+
distances[neighbor] = newDistance
59+
}
60+
}
61+
}
62+
63+
return distances
64+
}
65+
66+
func main() {
67+
// Create a graph.
68+
g := Graph{}
69+
g.AddEdge("A", "B", 1)
70+
g.AddEdge("A", "C", 4)
71+
g.AddEdge("B", "C", 2)
72+
g.AddEdge("B", "D", 5)
73+
g.AddEdge("C", "D", 1)
74+
g.AddEdge("D", "E", 3)
75+
g.AddEdge("E", "F", 2)
76+
77+
// Find the shortest distances from node "A" to all other nodes.
78+
shortestDistances := Dijkstra(g, "A")
79+
80+
// Print the shortest distances.
81+
for node, distance := range shortestDistances {
82+
fmt.Printf("Shortest distance from A to %s: %v\n", node, distance)
83+
}
84+
}

0 commit comments

Comments
 (0)