ACN-RIP Protocol
import java.util.*;
abstract class bell_ford
{
int MAX = 20;
int INFINITY = 9999;
int n;
int graph[][]=new int[MAX][MAX];
int start;
int distance[]=new int[MAX];
int predecessor[]=new int[MAX];
abstract void read_graph();
abstract void initialize();
abstract void update();
abstract void check();
abstract void algorithm();
}
class trial extends bell_ford
{
void read_graph()
{
Scanner kbd=new Scanner(System.in);
System.out.println(“Enter the no. of nodes in the graph ::”);
n=kbd.nextInt();
System.out.println(“Enter the adjacency matrix for the graph ::\n”);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
graph[i][j]=kbd.nextInt();
System.out.println(“Enter the start vertex ::”);
start=kbd.nextInt();
}
void initialize()
{
for(int i=1;i<=n;i++)
{
distance[i]=INFINITY;
predecessor[i]=0;
}
distance[start]=0;
}
void update()
{
for(int i=1;i<=n-1;i++)
{
for(int u=1;u<=n;u++)
{
for(int v=1;v<=n;v++)
{
if(graph[u][v]!=0)
{
if(distance[v]>distance[u]+graph[u][v])
{
distance[v]=distance[u]+graph[u][v];
predecessor[v]=u;
}
}
}
}
}
}
void check()
{
for(int u=1;u<=n;u++)
{
for(int v=1;v<=n;v++)
{
if(graph[u][v]!=0)
{
if(distance[v]>distance[u]+graph[u][v])
{
System.out.println(“does not exist’s “);
return;
}
}
}
}
System.out.println(“\n\nThere is no negative weight cycle and\n”);
System.out.println(“****** The final paths and the distacnes are ******\n\n”);
for(int i=1;i<=n;i++)
{
System.out.println(“path for node “+i+” is ::\n”);
int arr[] = new int[MAX];
int k=1;
int j=i;
while(predecessor[j]!=0)
{
arr[k]=predecessor[j];
k++;
j=predecessor[j];
}
for(k=k-1;k>0;k–)
System.out.println(arr[k]+”->”);
System.out.println(i);
System.out.println(“distance is “+distance[i]+”\n\n”);
}
}
void algorithm()
{
read_graph();
initialize();
update();
check();
}
public static void main(String args[])
{
trial obj=new trial();
obj.algorithm();
}
}