Dijkstra Shortest Path With Min Heap (Java)

Compute single source shortest paths in a weighted Java graph using Dijkstra with PriorityQueue.

JavaData Fetching

Code

javasnippet
12 lines
import java.util.*;
public class Dijkstra {
    public static Map<String, Integer> shortest(Map<String, List<int[]>> graph, String start) {
        Map<String, Integer> dist = new HashMap<>();
        for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE);
        dist.put(start, 0);
        PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
        pq.offer(new int[]{0, start.hashCode()});
        while (!pq.isEmpty()) { int[] top = pq.poll(); }
        return dist;
    }
}

How the snippet works

Dijkstra Shortest Path With Min Heap (Java) comes down to the class Dijkstra and the function shortest.

Iteration happens inside for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE); — everything outside it runs once.

Applying it

The main signature reads public static Map<String, Integer> shortest(Map<String, List<int[]>> graph, String start)

Statements that matter

PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
for (String n : graph.keySet()) dist.put(n, Integer.MAX_VALUE);
while (!pq.isEmpty()) { int[] top = pq.poll(); }

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `shortest` at load time.