Golang program to find the shortest path from a source node to a target node using the Bellman-Ford algorithm


Bellman-ford algorithm is used to find the shortest distance from the source node to the other nodes in a weighted directed graph. This algorithm also predicts the negative weight cycles in the graph. It has a time complexity of O(V*E) where V stands for vertices and E stands for edges.In this Golang article, we will write programs to find the shortest path from source node to a target node using the Bellman-ford algorithm.

Syntax

func range(variable)

The range function iterates through any data type. To utilise this, first type the range keyword followed by the data type to which we want to iterate, and the loop will iterate until the final element of the variable is reached. make ([] kind, size, and capacity)

func make ([] type, size, capacity)

The make function in Go is used to build an array/map. It receives as arguments the kind of variable to be generated, as well as its size and capacity.

Algorithm

  • Step 1 − Create the distance array.

  • Step 2 − Repeatedly relax the borders

  • Step 3 − Examine for negative weight cycles.

  • Step 4 − Find the shortest distances.

  • Step 5 − Determine the shortest distances.

Example

In this example, we will write a Go language program to find shortest path from source node to target node with the help of shortest path finder algorithm named Bellman-ford algorithm.

package main

import (
	"fmt"
	"math"
)

type Edge struct {
	source, target, weight int
}

func Bellman_ford(edges []Edge, num_vertices, source int, target int) ([]int, error) {

	distances := make([]int, num_vertices)
	for i := range distances {
		distances[i] = math.MaxInt32
	}
	distances[source] = 0

	for i := 0; i < num_vertices-1; i++ {
		for _, edge := range edges {
			if distances[edge.source]+edge.weight < distances[edge.target] {
				distances[edge.target] = distances[edge.source] + edge.weight
			}
		}
	}

	for _, edge := range edges {
		if distances[edge.source]+edge.weight < distances[edge.target] {
			return nil, fmt.Errorf("graph contains negative-weight cycle")
		}
	}
	return distances, nil
}

func main() {
	edges := []Edge{
		{0, 1, 4},
		{0, 2, 3},
		{1, 3, 2},
		{1, 4, 3},
		{1, 2, 1},
		{2, 1, 1},
		{2, 3, 4},
		{2, 4, 5},
		{4, 3, 2},
	}
	num_vertices := 5
	source := 0
	target := 3

	distances, err := Bellman_ford(edges, num_vertices, source, target)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Shortest distances from source to all vertices:")
	for i, distance := range distances {
		fmt.Printf("Vertex %d: %d\n", i, distance)
	}
	fmt.Printf("Shortest distance from source to target (vertex %d to vertex %d): %d\n", source, target, distances[target])
}

Output

Shortest distances from source to all vertices:
Vertex 0: 0
Vertex 1: 4
Vertex 2: 3
Vertex 3: 6
Vertex 4: 7
Shortest distance from source to target (vertex 0 to vertex 3): 6

Conclusion

In this article we have explored a program to find the shortest path from source vertex to the target node using the Bellman-ford algorithm. The method is simple and straightforward and can be used anytime depending on the demand of the problem in hand.

Updated on: 06-Jul-2023

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements