Program to find the shortest distance in the given graph in java.
Program Code:
import java.io.*;
import java.net.*;
import java.util.*;
class dj
{
public static void main(String ar[]) throws Exception
{ int i,j,n,temp,temp1,source,destination,tc,min;
BufferedReader d=new BufferedReader(new InputStreamReader(System.in));
int no[][]=new int[10][10];
System.out.println("Enter the number of nodes");
n=Integer.parseInt(d.readLine());
System.out.println("Enter the transition between the nodes");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print("Cost"+i+"-"+j+"-->");
no[i][j]=Integer.parseInt(d.readLine());
System.out.println();
}
}
System.out.println("Enter the source node");
source =Integer.parseInt(d.readLine());
temp1=source;
System.out.println("Enter the destination node");
destination=Integer.parseInt(d.readLine());
tc=0;
for(i=temp1;i<n;i++)
{min=1000;
for(j=0;j<n;j++)
{
temp=no[i][j];
if(i==j||no[i][j]==0)
continue;
else if(min>temp)
{min=temp;temp1=j;}
else if(temp1==destination)
break;
}
no[temp1][i]=0;
no[i][temp1]=0;
tc=tc+min;
}
if(no[source][destination]!=0)
{if(tc>no[source][destination])
tc=no[source][destination];
}
System.out.println("cost ="+tc);
}
Output:
}
0 comments:
Post a Comment