Go program to find the diameter of a graph using the Dijkstra Algorithm


In this article we will write a go language program to find the diameter of a graph. The diameter of a graph is the maximum distance between any two vertices in the graph. There are several Algorithms that can be used to find the diameter of a graph, including Dijkstra's Algorithm, Floyd-Warshall Algorithm, and Breadth-First Search Algorithm. Since, dijkastra Algorithm finds the shortest distance between source vertex and other vertices. We can also use it to find the largest distance by comparing the length of vertices recieved.

Syntax

func len(v Type) int

The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable.

Algorithm

  • Step 1 − First, we need to import the fmt and math packages. Then Define the edge struct which represents an edge in a graph with a to vertex and a weight.

  • Step 2 − Define the priorityQueue type as a slice of edge structs.

  • Step 3 − Define the dijkstra function which takes a graph represented as a 2D slice of edge structs and a starting vertex as arguments and returns the shortest distances from the starting vertex to all other vertices using Dijkstra's Algorithm.

  • Step 4 − Initialize a dist slice to store the shortest distances, with each element set to the maximum integer value.

  • Step 5 − Set the distance of the starting vertex to 0. Create a priority queue pq and push the starting vertex with a weight of 0 onto the queue.

  • Step 6 − If the distance to the neighbor through the popped vertex is less than the current shortest distance to the neighbor, update the distance and push the neighbor onto the priority queue.

  • Step 7 − Return the dist slice with the shortest distances to all vertices.

  • Step 8 − Define the getDiameter function and Initialize the start variable to the first vertex in the graph.

  • Step 9 − Calculate the shortest distances from the end vertex to all other vertices using dijkstra. Initialize the diameter variable to 0.

  • Step 10 − If the distance is greater than the current diameter and less than the maximum integer value, update the diameter. Return the diameter.

  • Step 11 − Now, start the main() function and define the edges. Further call the getDiameter() function by passing the edges as arguments and store the result obtained in a variable.

  • Step 12 − Print the result obtained on the screen

Example

In this Example we will write a go language program to find the diameter of a graph by using the dijkastra Algorithm. Dijkastra Algorithm is used to find the shortest path between vertices in a graph.

package main

import (
   "container/heap"
   "fmt"
   "math"
)

type edge struct {
   to     int
   weight int
}

type priorityQueue []edge

func (pq priorityQueue) Len() int {
   return len(pq)
}

func (pq priorityQueue) Less(i, j int) bool {
   return pq[i].weight < pq[j].weight
}

func (pq priorityQueue) Swap(i, j int) {
   pq[i], pq[j] = pq[j], pq[i]
}

func (pq *priorityQueue) Push(x interface{}) {
   *pq = append(*pq, x.(edge))
}

func (pq *priorityQueue) Pop() interface{} {
   old := *pq
   n := len(old)
   x := old[n-1]
   *pq = old[0 : n-1]
   return x
}

func dijkstra(graph [][]edge, start int) []int {
   dist := make([]int, len(graph))
   for i := range dist {
      dist[i] = math.MaxInt32
   }
   dist[start] = 0

   pq := make(priorityQueue, 0)
   heap.Push(&pq, edge{to: start, weight: 0})

   for pq.Len() > 0 {
      node := heap.Pop(&pq).(edge)
      if dist[node.to] < node.weight {
         continue
      }
      for _, e := range graph[node.to] {
         if nd := node.weight + e.weight; nd < dist[e.to] {
            dist[e.to] = nd
            heap.Push(&pq, edge{to: e.to, weight: nd})
         }
      }
   }
   return dist
}

func getDiameter(graph [][]edge) int {
   var start int
   for i := range graph {
      start = i
      break
   }
   dist := dijkstra(graph, start)

   var end int
   for i, d := range dist {
      if d < math.MaxInt32 && dist[end] < d {
         end = i
      }
   }
   dist = dijkstra(graph, end)

   var diameter int
   for _, d := range dist {
      if d > diameter && d < math.MaxInt32 {
         diameter = d
      }
   }
   return diameter
}

func main() {
   graph := [][]edge{
      {{1, 5}, {2, 3}},
      {{1, 5}, {2, 1}, {3, 6}, {4, 8}},
      {{1, 3}, {1, 1}, {4, 7}},
      {{1, 6}, {4, 9}},
      {{1, 8}, {2, 7}, {3, 9}},
   }
   fmt.Println("The given vertices are:", graph)
   diameter := getDiameter(graph)
   fmt.Println("Diameter obtained is:", diameter)
}

Output

The given vertices are: [[{1 5} {2 3}] [{1 5} {2 1} {3 6} {4 8}] [{1 3} {1 1} {4 7}] [{1 6} {4 9}] [{1 8} {2 7} {3 9}]]
Diameter obtained is: 9

Conclusion

In this article, we discussed method to find the diameter of a graph using the Dijkstra Algorithm in Go. This method is used to obtain the smallest length of vertices from the graph. To calculate the diameter we are comparing the distance of each vertex with the distance of the current value of diameter. If the distance is greater than the diameter then we need to update that value and continue till we get the largest distance which is actually the diameter of the circle.

Updated on: 05-Apr-2023

169 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements