Golang program to find shortest path between all pairs of nodes in a graph using dijikstra Algorithm


In this golang program article, we are going to learn how to use a struct Edge to represent a weighted edge in the graph, and the dijkstra function takes the number of nodes n and a slice of Edge objects as input. It returns a two-dimensional slice representing the distance matrix between all pairs of nodes in the graph

In this Golang article, we will explore how to implement Dijkstra's Algorithm in to find the shortest path between all pairs of nodes in a graph.

Algorithm

  • Step 1 − First, we need to import the fmt and math packages. Then Define an Edge struct to represent a weighted edge in the graph, with fields for the start node, end node, and edge weight.

  • Step 2 − Define a function dijkstra(n int, edges []Edge) [][]int that takes the number of nodes n and a slice of Edge objects as input, and returns a two-dimensional slice representing the distance matrix between all pairs of nodes in the graph.

  • Step 3 − Initialize an adjacency matrix adj of size n x n, and set all entries to infinity except for the diagonal entries, which are set to 0. Populate the adjacency matrix based on the edges in the input slice.

  • Step 4 − Initialize a distance matrix dist of size n x n, and copy the values from the adjacency matrix into it.

  • Step 5 − Compute the shortest path between all pairs of nodes using three nested loops. The outer loop iterates over all nodes k, and the inner loops iterate over all pairs of nodes i and j.

  • Step 6 − For each pair of nodes, check whether the distance from i to k plus the distance from k to j is less than the current distance from i to j. If so, update the distance matrix with the new shortest path distance and return the distance matrix.

  • Step 7 − Now, start the main() function. Inside the main() initialize an array by passing the edges of the graph as values to it.

  • Step 8 − Then call the dijkastra() function and pass the array initialized above as arguments to the function and store the result obtained in a variable.

  • Step 9 − At last print the result obtained which are the shortest path between all pairs of nodes in a graph.

Example

The following Example, represents the distance matrix between all pairs of nodes in the graph, where dist[i][j] represents the shortest path distance from node i to node j. For Example, dist[0][1] is 5, which means the shortest path from node 0 to node 1 has a weight of 5. Similarly, dist[2][3] is 1, which means the shortest path from node 2 to node 3 has a weight of 1.

package main

import (
   "fmt"
   "math"
)

type Edge struct {
   from int
   to   int
   cost int
}

func dijkstra(n int, edges []Edge) [][]int {
   // Initialize adjacency matrix
   adj := make([][]int, n)
   for i := 0; i < n; i++ {
      adj[i] = make([]int, n)
      for j := 0; j < n; j++ {
         if i == j {
            adj[i][j] = 0
         } else {
            adj[i][j] = math.MaxInt32
         }
      }
   }

   // Build adjacency matrix
   for _, e := range edges {
      adj[e.from][e.to] = e.cost
   }

   // Initialize distance matrix
   dist := make([][]int, n)
   for i := 0; i < n; i++ {
      dist[i] = make([]int, n)
      copy(dist[i], adj[i])
   }

   // Compute shortest path between all pairs
   for k := 0; k < n; k++ {
      for i := 0; i < n; i++ {
         for j := 0; j < n; j++ {
            if dist[i][k]+dist[k][j] < dist[i][j] {
               dist[i][j] = dist[i][k] + dist[k][j]
            }
         }
      }
   }
   return dist
}

func main() {
   n := 4
   edges := []Edge{
      {0, 1, 5},
      {0, 2, 10},
      {1, 2, 3},
      {2, 3, 1},
      {3, 0, 2},
   }
   fmt.Println("The given vertices of graph are:", edges)
   dist := dijkstra(n, edges)
   fmt.Println("The shortest distance between all pairs of nodes are:", dist)
}

Output

The given vertices of graph are: [{0 1 5} {0 2 10} {1 2 3} {2 3 1} {3 0 2}]
The shortest distance between all pairs of nodes are: [[0 5 8 9] [6 0 3 4] [3 8 0 1] [2 7 10 0]]

Conclusion

We have successfully compiled and executed a go language program to find the shortest path between all pairs of nodes in a graph by using the dijkastra Algorithm. Dijkstra's Algorithm is a powerful tool for computing shortest paths in graphs, and the Go implementation presented in this article provides a clear and simple way to apply the Algorithm to find the shortest path between all pairs of nodes in a graph.

Updated on: 05-Apr-2023

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements