Golang program to implement Bellman ford algorithm


The bellman ford algorithm is a graph traversal method that is used to find the shortest distance in a weighted network from a particular vertex to all the vertices. In this article, we will write a Go language program to implement Bellman ford algorithm. This algorithm is used to handle the situations where you need to find the shortest path from the source vertex to other vertices in a weighted directed graph. It works by updating the distance value of the vertices if the shortest path is found.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

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 − Create an Edge struct to represent an edge in the graph, with three fields source of type int, destination of type int and weight of type float.

  • Step 2 − Then, create a Graph struct to represent a weighted directed graph, with two fields - number of vertices of type int and a slice of edges.

  • Step 3 − Create a BellmanFord() function that takes a graph and source vertex as input and returns the arrays of distances and previous vertices

  • Step 4 − Then, initialize the distance array (dist[]) and previous vertex array (prev[]) for all vertices. Check whether a negative weight cycle exists with dist[u] + w is smaller than dist[v].

  • Step 5 − Create a PrintShortestPaths() function that prints the shortest paths from the source vertex to all other vertices

  • Step 6 − Then, construct the shortest path by traversing the previous vertices array starting and print distance and path. Create a main function and Initialize the source vertex with 0

  • Step 7 − Finally, execute the Bellman-Ford algorithm and obtain the distances and previous vertex arrays, if the arrays are not nil, print the shortest paths from the source vertex.

Example

In this article, we will write a Go language program to implement Bellman ford algorithm to find shortest path in a weighted directed graph.

package main

import (
   "fmt"
   "math"
)
type Edge struct {
   src    int     
   dest   int     
   weight float64 
}
type Graph struct {
   vertices int   
   edges    []Edge 
}
func InitGraph(vertices int) *Graph {
   return &Graph{
      vertices: vertices,
      edges:    make([]Edge, 0),
   }
}
func (g *Graph) AddEdge(src, dest int, weight float64) {
   g.edges = append(g.edges, Edge{src, dest, weight})
}
func BellmanFord(g *Graph, source int) ([]float64, []int) {
   dist := make([]float64, g.vertices) 
   prev := make([]int, g.vertices)     
   for i := 0; i < g.vertices; i++ {
      dist[i] = math.Inf(1) 
      prev[i] = -1        
   }
   dist[source] = 0 
  
   for i := 1; i < g.vertices; i++ {
      for _, edge := range g.edges {
         u := edge.src
         v := edge.dest
         w := edge.weight
         if dist[u]+w < dist[v] {
            dist[v] = dist[u] + w
            prev[v] = u
         }
      }
   }

   for _, edge := range g.edges {
      u := edge.src
      v := edge.dest
      w := edge.weight
      if dist[u]+w < dist[v] {
         fmt.Println("Graph contains a negative weight cycle")
         return nil, nil
      }
   }

   return dist, prev
}

func PrintShortestPaths(dist []float64, prev []int, source int) {
   fmt.Println("Shortest Paths from vertex", source)
   for i := 0; i < len(dist); i++ {
      if dist[i] == math.Inf(1) {
         fmt.Printf("Vertex %d is not reachable\n", i)
      } else {
         path := []int{}
         j := i
         for j != -1 {
            path = append([]int{j}, path...)
            j = prev[j]
         }
         fmt.Printf("Vertex %d: Distance=%f, Path=%v\n", i, dist[i], path)
      }
   }
}

func main() {
   g := InitGraph(5)

   g.AddEdge(0, 1, 6)
   g.AddEdge(0, 2, 7)
   g.AddEdge(1, 2, 8)
   g.AddEdge(1, 3, -4)
   g.AddEdge(1, 4, 5)
   g.AddEdge(2, 3, 9)
   g.AddEdge(2, 4, -3)
   g.AddEdge(3, 1, 7)
   g.AddEdge(4, 0, 2)
   g.AddEdge(4, 3, 7)

   source := 0
   dist, prev := BellmanFord(g, source)
   if dist != nil && prev != nil {
      PrintShortestPaths(dist, prev, source)
   }
}

Output

Shortest Paths from vertex 0
Vertex 0: Distance=0.000000, Path=[0]
Vertex 1: Distance=6.000000, Path=[0 1]
Vertex 2: Distance=7.000000, Path=[0 2]
Vertex 3: Distance=2.000000, Path=[0 1 3]
Vertex 4: Distance=4.000000, Path=[0 2 4]

Conclusion

In this article, we have executed the program for implementing Bellman-ford algorithm using structs. We explored the working of this algorithm and also saw how to represent a graph using an adjacency list.

Updated on: 05-Jul-2023

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements