/** * Sequential Version of Dijkstra's Algorithm */ import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; import java.util.TreeMap; import java.util.List; public class DijkstraColSeq { private final static Integer infinity = 2000; static int len = 0; /** * @param args * 0 - Filename where Vertices and Edges are stored * @param args * 1 - Name of the source vertex * @param args * 2 - Name of the destination vertex */ public static void main(String[] args) { String fileName = null; Vertex source = null; Vertex destination = null; if (args.length == 3) { fileName = args[0]; source = new Vertex(Integer.parseInt(args[1])); destination = new Vertex(Integer.parseInt(args[2])); } else { System.err.println("Invalid command-line arguements"); System.exit(0); } List vertices = new ArrayList(); ArrayList edges = new ArrayList(); try { BufferedReader in = new BufferedReader(new FileReader(fileName)); String line = in.readLine(); len = Integer.parseInt( line ); while ((line = in.readLine()) != null) { Scanner scan = new Scanner( line ); Vertex start = new Vertex( scan.nextInt() ); Vertex end = new Vertex( scan.nextInt() ); if( !vertices.contains( start ) ) vertices.add( start ); if( !vertices.contains( end ) ) vertices.add( end ); edges.add( new Edge( start, end, scan.nextInt() ) ); } in.close(); } catch( Exception e ) { e.printStackTrace(); } Graph g = new Graph(vertices, edges); //*** Dijkstra's Algorithm ***\\ TreeMap distFromSource = new TreeMap(); TreeMap previousNode = new TreeMap(); TreeMap unvisitedNodes = new TreeMap(); for( Vertex v : g.getVertices() ) { distFromSource.put( v, infinity ); previousNode.put( v, null ); unvisitedNodes.put( v, null ); } distFromSource.put(source, 0); for( Vertex v : unvisitedNodes.keySet() ) { Vertex currentNode = v; for( Vertex v2 : unvisitedNodes.keySet() ) { if( distFromSource.get( v2 ) < distFromSource.get( currentNode ) && unvisitedNodes.get( v2 ) == null ) currentNode = v2; } unvisitedNodes.put( currentNode, new Integer( 1 ) ); for( Edge e : g.getEdgesContaining( currentNode ) ) { int newDist = distFromSource.get( currentNode ) + e.getDistance(); Vertex otherVertex = e.getOtherVertex( currentNode ); if( newDist < distFromSource.get( otherVertex ) ) { distFromSource.put( otherVertex, newDist ); previousNode.put( otherVertex, currentNode ); } } } Vertex prev = previousNode.get( destination ); String output = "[" + destination.getName() + "]"; while( !source.equals( prev ) ) { output = "[" + prev.getName() + "] -> " + output; prev = previousNode.get( prev ); } output = "[" + source.getName() + "] -> " + output + " (Total Distance = " + distFromSource.get( destination ) + ")"; System.out.println( output ); } }