Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Bellman Ford Algorithm, Assignments of Computer Networks

The document briefly explains the Bellman Ford algorithm along with the code in Java language. Output screenshots have also been attached for more reference

Typology: Assignments

2019/2020

Uploaded on 11/16/2020

rogerbravo07
rogerbravo07 🇮🇳

1 document

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Bellman Ford Algorithm:
Bellman Ford algorithm helps us find the shortest path from a vertex to all other
vertices of a weighted graph.
It works correctly when some of the edges of the directed graph G may have negative
weight. When there are no cycles of negative weight, we can find the shortest path
between source and destination.
It is slower than Dijkstra’s Algorithm but more versatile as it is capable of handling
some of the negative weight edges.
Based on the ‘Principle of Relaxation’ in which more accurate values gradually
recovered an approximation to the proper distance by until eventually reaching the
optimal solution.
Flowchart:
pf3
pf4
pf5

Partial preview of the text

Download Bellman Ford Algorithm and more Assignments Computer Networks in PDF only on Docsity!

Bellman Ford Algorithm:

 Bellman Ford algorithm helps us find the shortest path from a vertex to all other vertices of a weighted graph.  It works correctly when some of the edges of the directed graph G may have negative weight. When there are no cycles of negative weight, we can find the shortest path between source and destination.  It is slower than Dijkstra’s Algorithm but more versatile as it is capable of handling some of the negative weight edges.  Based on the ‘Principle of Relaxation’ in which more accurate values gradually recovered an approximation to the proper distance by until eventually reaching the optimal solution.

Flowchart:

CODE:

import java.util.Scanner; class BellmanFord { private int d[]; private int n; public static final int MAX_VALUE=999; public BellmanFord(int n) { this.n=n; d= new int[n+1]; } public void BellmanFordEval(int source,int a[][]) { for(int node=1;node<=n;node++) { d[node]=MAX_VALUE; } d[source]=0; for(int node=1;node<=n-1;node++) { for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(a[i][j]!=MAX_VALUE) {

n=sc.nextInt(); int a[][]=new int[n+1][n+1]; System.out.println("Enter the adjacency matrix"); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { a[i][j]=sc.nextInt(); if(i==j) { a[i][j]=0; continue; } if(a[i][j]==0) { a[i][j]=MAX_VALUE; } } } System.out.println("Enter the source vertex"); source=sc.nextInt(); BellmanFord bellmanford=new BellmanFord(n); bellmanford.BellmanFordEval(source,a); sc.close(); } }

OUTPUT:

EXAMPLE 1:

EXAMPLE 2: