Implementing Dijkstra


Problem Definition

Link : Implementing Dijkstra

You are given a graph represented using an adjacency matrix or adjacency list, and a source vertex S. Find the shortest path from the source to all vertices using Dijkstra’s Algorithm.


Intuition Behind Dijkstra's Algorithm

Dijkstra’s algorithm is a greedy shortest path algorithm designed for non-negative weight graphs. It maintains a set of nodes whose minimum distance from the source is already known and iteratively selects the closest unvisited node to explore.

Core Idea:

At every step, pick the node with the minimum known distance and expand it, because no other unexplored path can improve it (greedy selection).


Why Not Use BFS?

BFS only works for unweighted graphs or unit weights. In weighted graphs:

So, BFS doesn’t account for the weight of edges—this is where Dijkstra is necessary.


Data Structure Choices

Using PriorityQueue (Java Min-Heap)

PriorityQueue<Pair> pq = new PriorityQueue<>((a,b) -> a.dist - b.dist);

Using Set (C++ std::set or TreeSet Equivalent)

Alternative: Use PriorityQueue with a distance array to skip outdated entries.

Why Not Use Simple Queue?


Algorithm Steps (Adjacency List Version)

  1. Initialize a distance array dist[] of size V with Integer.MAX_VALUE.

  2. Set dist[src] = 0.

  3. Create a min-heap (PriorityQueue) storing (distance, node).

  4. While the queue is not empty:

    • Pop the node with the smallest distance.

    • For each neighbor:

      • If dist[curr] + weight < dist[adj], update it and push into the heap.

Java Code (Using PriorityQueue)

class Solution {
    static class Pair {
        int node, dist;
        Pair(int node, int dist) {
            this.node = node;
            this.dist = dist;
        }
    }

    static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S) {
        int[] dist = new int[V];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[S] = 0;

        PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> a.dist - b.dist);
        pq.add(new Pair(S, 0));

        while (!pq.isEmpty()) {
            Pair curr = pq.poll();
            int u = curr.node;
            int d = curr.dist;

            for (ArrayList<Integer> neighbor : adj.get(u)) {
                int v = neighbor.get(0);
                int weight = neighbor.get(1);

                if (dist[u] + weight < dist[v]) {
                    dist[v] = dist[u] + weight;
                    pq.add(new Pair(v, dist[v]));
                }
            }
        }

        return dist;
    }
}

Dry Run

Input:

V = 4
Edges:
0 → 1 (1)
0 → 2 (4)
1 → 2 (2)
1 → 3 (6)
2 → 3 (3)

Start from S = 0:

Final distances: [0, 1, 3, 6]


Time and Space Complexity

Let:

Using PriorityQueue (Min Heap):

Why E Can Be Up to V²?


Applications


Why TreeSet Fails in Java

Java's TreeSet:

Result: You could accidentally skip a node that’s critical for reaching the shortest path.

Better Practice: