TOPIC: dijkstra's algorithm in java
*/
import java.util.*;
public class dij
{
public static void main(String args[])
{
int d[][]={{0,9,3,0,0,0},
{2,0,6,5,3,0},
{3,6,0,0,1,0},
{0,5,0,0,2,2},
{0,3,1,1,0,4},
{0,0,0,2,4,0}};
int vi[][]=new int[6][6];
Vector v=new Vector();
int s=0,de=5,c=0,cost=-1,co=0,temp=0;
while(de!=c)
{
for(int i=-1;i<=5;i++)
{
while(cost<=0)
{cost=d[++i][c]; temp=i;}
if(d[de][c]>0 && vi[de][c]==0)
{ cost=d[de][c]; vi[de][c]=1; temp=de; break;}
else
{
if(d[i][c]!=0 && d[i][c]<cost && vi[i][c]==0)
{ cost=d[i][c]; vi[i][c]=1; temp=i; }
}
}
c=temp;
co=co+cost;
cost=-1;
v.add(c+1);
}
System.out.print("\nCost is : "+co);
System.out.println("\nPath is: ");
System.out.print(s+1+" ");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.print(e.nextElement()+" ");
System.out.print("");
}
}
/*
Cost is : 9
Path is:
1 2 5 6
*/
No comments:
Post a Comment