Dijkstra's Algorithm Single Source Shortest Path in DSA C - Time & Space Complexity
We want to understand how the time needed by Dijkstra's algorithm changes as the graph size grows.
Specifically, how the number of nodes and edges affects the work done to find shortest paths.
Analyze the time complexity of the following Dijkstra's algorithm code snippet.
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] > 0 && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
}
This code finds shortest paths from one node to all others using a simple array and adjacency matrix.
Look at the loops and repeated steps:
- Primary operation: The outer loop runs once for each node (V times).
- Nested operation: Inside, it finds the minimum distance node (scans all V nodes).
- Inner loop: For each chosen node, it checks all neighbors (V nodes) to update distances.
- Dominant work: The nested loops scanning all nodes make the main cost.
As the number of nodes (V) grows, the work grows roughly with the square of V.
| Input Size (V) | Approx. Operations |
|---|---|
| 10 | About 100 (10 x 10) checks |
| 100 | About 10,000 (100 x 100) checks |
| 1000 | About 1,000,000 (1000 x 1000) checks |
Pattern observation: Doubling nodes roughly quadruples the work because of nested loops.
Time Complexity: O(V2)
This means the time needed grows roughly with the square of the number of nodes in the graph.
[X] Wrong: "Dijkstra's algorithm always runs in linear time because it just visits each node once."
[OK] Correct: The algorithm repeatedly scans all nodes to find the closest unvisited node and updates neighbors, causing nested loops that increase time with the square of nodes.
Understanding this time complexity helps you explain how your solution scales and why using better data structures can improve performance.
"What if we replace the array with a priority queue (min-heap) to find the minimum distance node? How would the time complexity change?"
Practice
Solution
Step 1: Understand the goal of Dijkstra's Algorithm
Dijkstra's Algorithm is designed to find the shortest distance from one starting point (source) to every other point in a graph with non-negative edge weights.Step 2: Compare with other graph algorithms
Minimum spanning tree algorithms find a tree connecting all vertices with minimum total edge weight, cycle detection finds loops, and topological sort orders vertices in directed acyclic graphs. These are different goals.Final Answer:
To find the shortest path from a single source to all other vertices -> Option DQuick Check:
Dijkstra's Algorithm = shortest paths from source [OK]
- Confusing with minimum spanning tree algorithms
- Thinking it detects cycles
- Assuming it sorts vertices
Solution
Step 1: Understand distance initialization
Distances should start as infinity (or a very large number) except the source vertex, to represent unknown shortest paths.Step 2: Check each option
int dist[V] = {0}; initializes all distances to 0, which is incorrect. int dist[V]; for(int i=0; iFinal Answer:
int dist[V]; for(int i=0; i -> Option AQuick Check:
Initialize distances to INT_MAX with loop [OK]
- Using {INT_MAX} initializes only first element
- Setting all distances to 0
- Assigning NULL to int array
int graph[4][4] = {
{0, 1, 4, 0},
{1, 0, 2, 6},
{4, 2, 0, 3},
{0, 6, 3, 0}
};Solution
Step 1: Initialize distances and start from vertex 0
Distances: dist[0]=0, dist[1]=∞, dist[2]=∞, dist[3]=∞. Update neighbors of 0: dist[1]=1, dist[2]=4.Step 2: Pick vertex with smallest tentative distance and update neighbors
Pick vertex 1 (dist=1). Update dist[2] = min(4, 1+2=3) = 3, dist[3] = min(∞, 1+6=7) = 7. Next pick vertex 2 (dist=3). Update dist[3] = min(7, 3+3=6) = 6. Finally pick vertex 3 (dist=6).Final Answer:
[0, 1, 3, 6] -> Option CQuick Check:
Distances after relaxation = [0,1,3,6] [OK]
- Not updating distances after relaxation
- Choosing wrong next vertex
- Ignoring shorter paths through intermediate vertices
for (int count = 0; count < V-1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = 1;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}Solution
Step 1: Analyze edge existence condition
The condition 'graph[u][v]' relies on implicit truthiness of non-zero values. In C, this works but is less clear. Using 'graph[u][v] != 0' explicitly checks for edge presence and improves readability.Step 2: Check other conditions
Loop range from 0 to V-1 is correct for V vertices. sptSet should start with 0 (false). The dist[u] check must be '!= INT_MAX' to ensure u is reachable before relaxing edges.Final Answer:
The condition 'graph[u][v]' should be 'graph[u][v] != 0' to check edge existence -> Option BQuick Check:
Explicit edge check improves clarity [OK]
- Assuming loop range is wrong
- Initializing sptSet incorrectly
- Reversing dist[u] check logic
0-1: 7, 0-2: 9, 0-5: 14, 1-2: 10, 1-3: 15, 2-3: 11, 2-5: 2, 3-4: 6, 4-5: 9
Using Dijkstra's Algorithm from source 0, what is the shortest distance to vertex 4?
Solution
Step 1: Initialize distances and start from vertex 0
dist[0]=0, others = ∞. Update neighbors: dist[1]=7, dist[2]=9, dist[5]=14.Step 2: Pick vertex with smallest dist and update neighbors
Pick 1 (7): update dist[3] = min(∞, 7+15=22) = 22. Pick 2 (9): update dist[3] = min(22, 9+11=20) = 20, dist[5] = min(14, 9+2=11) = 11. Pick 5 (11): update dist[4] = min(∞, 11+9=20) = 20. Pick 3 (20): update dist[4] = min(20, 20+6=26) = 20. Pick 4 (20).Final Answer:
20 -> Option AQuick Check:
Shortest path to 4 = 20 [OK]
- Not updating dist[5] to smaller value
- Ignoring shorter path through vertex 2
- Adding edges incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
