/*********************************** * Dijstra's Algorithm in Java * * * * Matt Smart (mjs@cs.bham.ac.uk) * * March 23, 2007 * ***********************************/ import java.util.*; public class Dijkstra { //define some constants /** "Infinity" (represented by MAX_VALUE) */ public static final int INF=Integer.MAX_VALUE; /** Number of Vertices in Graph */ public static final int NUM_VERTICES=8; //now define the cities /** Constant representing Honalulu */ public static final int HNL=0; /** Constant representing San Francisco */ public static final int SFO=1; /** Constant representing Los Angeles */ public static final int LAX=2; /** Constant representing Zorg En Hoop, Suriname */ public static final int ORG=3; /** Constant representing Dallas Fort Worth */ public static final int DFW=4; /** Constant representing La Guardia, New York */ public static final int LGA=5; /** Constant representing T.F. Green, Providence */ public static final int PVD=6; /** Constant representing Miami */ public static final int MIA=7; /** Constant representing a Non-Existent airport */ public static final int nonexistent=8; //start and end vertices /** The first vertex in the array */ public static final int FIRST_VERTEX=HNL; /** The last vertex in the array */ public static final int LAST_VERTEX=MIA; //list of names of cities, for output private String[] name={"HNL","SFO","LAX","ORD","DFW","LGA","PVD","MIA"}; //now the initial distance matrix ("weight") private int weight[][]= { /* HNL SFO LAX ORD DFW LGA PVD MIA */ {0, INF, 2555, INF, INF, INF, INF, INF }, //HNL {INF, 0, 337, 1843, INF, INF, INF, INF }, //SFO {2555, 337, 0, 1743, 1233, INF, INF, INF }, //LAX {INF, 1843, 1742, 0, 802, INF, 849, INF }, //ORD {INF, INF, 1233, 802, 0, 1387, INF, 1120}, //DFW {INF, INF, INF, INF, 1387, 0, 142, 1099}, //LGA {INF, INF, INF, 849, INF, 142, 0, 1205}, //PVD {INF, INF, INF, INF, 1120, 1099, 1205, 0 }, //MIA }; /*** Dijkstra's Algorithm starts here ***/ int[] distance=new int[NUM_VERTICES]; boolean[] tight=new boolean[NUM_VERTICES]; int[] predecessor=new int[NUM_VERTICES]; /** * Returns the Vertex (or one of the Vertices) that has minimal weight * and is not already tight * @return Vertex with minimal weight that is non-tight */ private int minimalNontight(){ int j,u; for(j=FIRST_VERTEX; j st=new Stack(); for(int v=destination; v!=origin; v=predecessor[v]) if(v==nonexistent){ System.out.println("non-existent (because the graph is not connected)."); return; }else{ st.push(v); } st.push(origin); while(!st.empty()) System.out.print(name[st.pop()]+" -> "); System.out.println("[finished]"); } /** * Constructor (unused) */ public Dijkstra(){ return; } public static void main(String[] unused){ new Dijkstra().printShortestPath(SFO, MIA); } }