Skip to content

Commit fb80859

Browse files
author
phishman3579
committed
Added comments to the Dijkstra's algorithm
git-svn-id: https://java-algorithms-implementation.googlecode.com/svn/trunk@57 032fbc0f-8cab-eb90-e552-f08422b9a96a
1 parent 9e2ac44 commit fb80859

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

src/com/jwetherell/algorithms/graph/Dijkstra.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ public static CostPathPair getShortestPath(Graph g, Graph.Vertex start, Graph.Ve
4444
costs.add(new CostVertexPair(Integer.MAX_VALUE,v));
4545
}
4646

47+
// Dijkstra's algorithm only works on positive cost graphs
4748
boolean hasNegativeEdge = checkForNegativeEdges(unvisited);
4849
if (hasNegativeEdge) throw (new IllegalArgumentException("Negative cost Edges are not allowed."));
4950

@@ -52,38 +53,46 @@ public static CostPathPair getShortestPath(Graph g, Graph.Vertex start, Graph.Ve
5253
while (vertex!=null && !vertex.equals(end)) {
5354
Queue<Graph.Edge> queue = new PriorityQueue<Graph.Edge>();
5455
for (Graph.Edge e : vertex.getEdges()) {
56+
// Only add vertices which haven't been visited
5557
if (unvisited.contains(e.getToVertex())) queue.add(e);
5658
}
59+
60+
// Compute costs from current vertex to all reachable vertices which haven't been visited
5761
for (Graph.Edge e : queue) {
5862
CostVertexPair pair = getPairForVertex(e.getToVertex());
5963
CostVertexPair lowestCostToThisVertex = getPairForVertex(vertex);
6064
int cost = lowestCostToThisVertex.cost + e.getCost();
6165
if (pair.cost==Integer.MAX_VALUE) {
66+
// Haven't seen this vertex yet
6267
pair.cost = cost;
6368
Set<Graph.Vertex> set = path.get(e.getToVertex());
6469
set.addAll(path.get(e.getFromVertex()));
6570
set.add(e.getFromVertex());
6671
} else if (cost<pair.cost) {
72+
// Found a shorter path to a reachable vertex
6773
pair.cost = cost;
6874
Set<Graph.Vertex> set = path.get(e.getToVertex());
6975
set.clear();
7076
set.addAll(path.get(e.getFromVertex()));
7177
set.add(e.getFromVertex());
7278
}
7379
}
80+
// We have visited this vertex, remove it from the list
7481
unvisited.remove(vertex);
7582

83+
// If there are other vertices from this vertex to visit (which haven't been visited yet)
7684
if (queue.size()>0) {
7785
Graph.Edge e = queue.remove();
7886
previous = vertex;
7987
vertex = e.getToVertex();
8088
} else {
81-
// You can't get there from here.
89+
// No vertices available from this vertex or all vertices from here have been visited
8290
vertex = previous;
8391
}
8492
}
8593

8694
CostVertexPair pair = getPairForVertex(end);
95+
// Add the end vertex to the Set, just to make it more understandable.
8796
Set<Graph.Vertex> set = path.get(end);
8897
set.add(end);
8998

0 commit comments

Comments
 (0)