Skip to main content

Write a program to find the shortest path between vertices using bellman-ford algorithm.


import java.io.*;
import java.util.*;
public class Bellmanford
 {
public static final int max=999;
 public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int k[ ]=new int[10];
int a[][ ]=new int[30][30];
System.out.println("bellmanford algorithm implementation ");
System.out.println("Enter the no. of nodes");
int  n=s.nextInt();
System.out.println("Enter the adjacency matrix ");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
a[i][j]=s.nextInt();
if(a[i][j]==0)
{
a[i][j]=max;
}
}
}
System.out.println("\n Entered  matrix is: ");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println("Enter the destination vertex");
int  d=s.nextInt();
if(d<=n)
{
for(int v=1;v<=n;v++)
{
k[v]=max;
}
k[d]=0;
for(int v=1;v<n-1;v++)
{
for(int x=1;x<=n;x++)
{
for(int y=1;y<=n;y++)
{
if(a[x][y]!=max)
{
if(k[y]>k[x]+a[x][y])
            k[y]=k[x]+a[x][y];
}
}
}
}
for(int x=1;x<=n;x++)
{
for(int y=1;y<=n;y++)
{
if(a[x][y]!=max)
{
if(k[y]>k[x]+a[x][y])
System.out.println("negetive edge cycle:");
}
}
}
for(int r=1;r<=n;r++)
{
System.out.println("minimum distance from node "+r+" to node " +d+ " is " +k[r]);
}
}
}
}

Comments

Popular posts from this blog

Write a program for error detecting code using CRC-CCITT (16- bits).

import java.io.*; import java.util.*; public class CRC   {   public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.println("Enter the no of bits : "); int   n=s.nextInt(); int data[ ]=new int[n]; System.out.println("Enter the data bits : "); for(int i=0;i<n;i++) data[i]=s.nextInt(); System.out.println("Enter the no of divisor bits : "); int m=s.nextInt(); int divisor[ ]=new int[m]; System.out.println("Enter divisor bits : "); for(int j=0;j<m;j++) divisor[j]=s.nextInt(); int len=n+m-1; int div[ ]=new int[len]; int rem[ ]=new int[len]; int crc[ ]=new int[len]; int src[ ]=new int[len]; for(int i=0;i<data.length;i++) div[i]=data[i]; System.out.println("Dividend after appending zero"); for(int i=0;i<div.length;i++) System.out.print(div[i]); System.out.println(); for(int j=0;j<div.length;j++) rem[j]=div[j]; rem=divid...

Write a program for congestion control using leaky bucket algorithm

import java.util.*; public class LBA {        public static void main(String[] args ) {              // TODO Auto-generated method stub              int op ;              Scanner s = new Scanner(System. in );              int bktcap =0;              int remain =0;              int pkt []= new int [10];              System. out .println( "Enter Bucket size" );              bktcap = s .nextInt();         ...