Here is the program to find the shortest path between two nodes using Dijkastra algorithm
import java.io.*;
class MyDijkastra3
{
public static void main(String args[]) throws Exception
{
int n,i,j,tc,temp,current,source,destination,minimum;
int nodes[]=new int[20];
int cost[]=new int[10];
int distance[][]= new int[20][20];
tc=0;temp=0;int f=0;
DataInputStream d = new DataInputStream(System.in);
System.out.println("Enter the number of nodes(max 30)");
n =Integer.parseInt(d.readLine());
System.out.println("Enter the costs to each node(if there is no path between two nodes put distance -1");
for( i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.println("Cost"+i+"-"+j+"-->");
distance[i][j] = Integer.parseInt(d.readLine());
}
}
System.out.println("Enter the source node");
source =Integer.parseInt(d.readLine());
System.out.println("Enter the destination node");
destination=Integer.parseInt(d.readLine());
current=source;
minimum=1000;
for( i=current;i<=n;i++)
{
for(j=1;j<=n;j++)
{ if((i==j )|| (distance[i][j]==-1))
{continue;
}
else if(minimum>=distance[i][j])
{
minimum= distance[i][j];
current=j;
}
if(current==destination)
{System.out.println("Complete");f=1;
break;
}
}tc=tc+minimum;
minimum=10000;
distance[i][current]=-1;
distance[current][i]=-1;
if(f==1)
{
break;
}
}
if((distance[source][destination]!=0)&&(distance[source][destination]!=-1))
{if(distance[source][destination]<tc)
tc=distance[source][destination];
}
System.out.println("The total min cost from"+ source +"to"+ destination +"is:"+tc);
}}
0 comments:
Post a Comment