1313import com .jwetherell .algorithms .data_structures .Graph ;
1414
1515
16+ /**
17+ * Dijkstra's shortest path. Returns a tuple of total cost of shortest path and the path.
18+ *
19+ * @author Justin Wetherell <phishman3579@gmail.com>
20+ */
1621public class Dijkstra {
1722
1823 private static List <Graph .Vertex > unvisited = null ;
1924 private static List <CostVertexPair > costs = null ;
2025 private static Map <Graph .Vertex , Set <Graph .Vertex >> path = null ;
2126
2227 private Dijkstra () { }
23-
28+
2429 public static CostPathPair getShortestPath (Graph g , Graph .Vertex start , Graph .Vertex end ) {
2530 if (g ==null ) throw (new NullPointerException ("Graph must be non-NULL." ));
2631
@@ -32,13 +37,13 @@ public static CostPathPair getShortestPath(Graph g, Graph.Vertex start, Graph.Ve
3237 path .put (v , new LinkedHashSet <Graph .Vertex >());
3338 }
3439 path .get (start ).add (start );
35-
40+
3641 costs = new ArrayList <CostVertexPair >();
3742 costs .add (new CostVertexPair (0 ,start ));
3843 for (Graph .Vertex v : unvisited ) {
3944 costs .add (new CostVertexPair (Integer .MAX_VALUE ,v ));
4045 }
41-
46+
4247 boolean hasNegativeEdge = checkForNegativeEdges (unvisited );
4348 if (hasNegativeEdge ) throw (new IllegalArgumentException ("Negative cost Edges are not allowed." ));
4449
@@ -81,7 +86,7 @@ public static CostPathPair getShortestPath(Graph g, Graph.Vertex start, Graph.Ve
8186 CostVertexPair pair = getPairForVertex (end );
8287 Set <Graph .Vertex > set = path .get (end );
8388 set .add (end );
84-
89+
8590 return (new CostPathPair (pair .cost ,set ));
8691 }
8792
@@ -100,7 +105,7 @@ private static CostVertexPair getPairForVertex(Graph.Vertex v) {
100105 }
101106 return null ;
102107 }
103-
108+
104109 private static class CostVertexPair implements Comparable <CostVertexPair > {
105110
106111 private int cost = Integer .MAX_VALUE ;
@@ -126,17 +131,17 @@ public String toString() {
126131 return builder .toString ();
127132 }
128133 }
129-
134+
130135 public static class CostPathPair {
131136
132137 private int cost = 0 ;
133138 private Set <Graph .Vertex > path = null ;
134-
139+
135140 public CostPathPair (int cost , Set <Graph .Vertex > path ) {
136141 this .cost = cost ;
137142 this .path = path ;
138143 }
139-
144+
140145 @ Override
141146 public String toString () {
142147 StringBuilder builder = new StringBuilder ();
0 commit comments