Dijkstra's algorithm: Difference between revisions

Line 1,196:
This implementation finds the single path from a source to all reachable vertices.
Building the graph from a set of edges takes O(E log V) for each pass.
Vertices are stored in a PriorityQueueTreeSet (effectivelybinary heap) instead of a PriorityQueue (a balanced binary heap), givingin order to get O(E log V) performance for removal of any element, not just the head.
Decreasing the distance of a vertex is accomplished by removing it from the heap and later re-inserting it.
The former takes linear time, resulting in a potential bottleneck.
Use of a Fibonacci heap (which doesn't exist in the standard Java library) would alleviate this issue.
<lang java>
import java.io.*;
Line 1,292 ⟶ 1,290:
}
final Vertex source = graph.get(startName);
PriorityQueueNavigableSet<Vertex> q = new PriorityQueueTreeSet<>(graph.size());
// set-up vertices
Line 1,304 ⟶ 1,302:
}
/** Implementation of dijkstra's algorithm using a prioritybinary queueheap. */
private void dijkstra(final PriorityQueueNavigableSet<Vertex> q) {
Vertex u, v;
while (!q.isEmpty()) {
u = q.pollpollFirst(); // vertex with shortest distance (first iteration will return source)
if (u.dist == Integer.MAX_VALUE) break; // we can ignore u (and any other remaining vertices) since they are unreachable
41

edits