@@ -44,6 +44,7 @@ public static CostPathPair getShortestPath(Graph g, Graph.Vertex start, Graph.Ve
44
44
costs .add (new CostVertexPair (Integer .MAX_VALUE ,v ));
45
45
}
46
46
47
+ // Dijkstra's algorithm only works on positive cost graphs
47
48
boolean hasNegativeEdge = checkForNegativeEdges (unvisited );
48
49
if (hasNegativeEdge ) throw (new IllegalArgumentException ("Negative cost Edges are not allowed." ));
49
50
@@ -52,38 +53,46 @@ public static CostPathPair getShortestPath(Graph g, Graph.Vertex start, Graph.Ve
52
53
while (vertex !=null && !vertex .equals (end )) {
53
54
Queue <Graph .Edge > queue = new PriorityQueue <Graph .Edge >();
54
55
for (Graph .Edge e : vertex .getEdges ()) {
56
+ // Only add vertices which haven't been visited
55
57
if (unvisited .contains (e .getToVertex ())) queue .add (e );
56
58
}
59
+
60
+ // Compute costs from current vertex to all reachable vertices which haven't been visited
57
61
for (Graph .Edge e : queue ) {
58
62
CostVertexPair pair = getPairForVertex (e .getToVertex ());
59
63
CostVertexPair lowestCostToThisVertex = getPairForVertex (vertex );
60
64
int cost = lowestCostToThisVertex .cost + e .getCost ();
61
65
if (pair .cost ==Integer .MAX_VALUE ) {
66
+ // Haven't seen this vertex yet
62
67
pair .cost = cost ;
63
68
Set <Graph .Vertex > set = path .get (e .getToVertex ());
64
69
set .addAll (path .get (e .getFromVertex ()));
65
70
set .add (e .getFromVertex ());
66
71
} else if (cost <pair .cost ) {
72
+ // Found a shorter path to a reachable vertex
67
73
pair .cost = cost ;
68
74
Set <Graph .Vertex > set = path .get (e .getToVertex ());
69
75
set .clear ();
70
76
set .addAll (path .get (e .getFromVertex ()));
71
77
set .add (e .getFromVertex ());
72
78
}
73
79
}
80
+ // We have visited this vertex, remove it from the list
74
81
unvisited .remove (vertex );
75
82
83
+ // If there are other vertices from this vertex to visit (which haven't been visited yet)
76
84
if (queue .size ()>0 ) {
77
85
Graph .Edge e = queue .remove ();
78
86
previous = vertex ;
79
87
vertex = e .getToVertex ();
80
88
} else {
81
- // You can't get there from here.
89
+ // No vertices available from this vertex or all vertices from here have been visited
82
90
vertex = previous ;
83
91
}
84
92
}
85
93
86
94
CostVertexPair pair = getPairForVertex (end );
95
+ // Add the end vertex to the Set, just to make it more understandable.
87
96
Set <Graph .Vertex > set = path .get (end );
88
97
set .add (end );
89
98
0 commit comments