Dijkstra's Algorithm — Shortest Path Step by Step — Complete Beginner Guide
Learning Objectives
- State Dijkstra preconditions clearly
- Relax edges with a priority queue
- Track distances and parent pointers
- Reconstruct the shortest path
- Explain complexity and failure cases
What Problem Does Dijkstra Solve?
Dijkstra finds the shortest path from one source vertex to every other vertex in a graph with non-negative edge weights.
It is the classic tool for road maps, network latency, and game pathfinding.
| Requirement | Rule |
|---|---|
| Weights | Non-negative only |
| Source | One start vertex |
| Output | Distances and often parents |
| Graph type | Directed or undirected |
If any edge weight is negative, use Bellman-Ford instead because Dijkstra can finalize the wrong distance.
Core Idea
Keep the best-known distance to every vertex. Always expand the unsettled vertex with the smallest tentative distance. When popped from a min-priority queue with non-negative weights, its distance is final.
Then relax each outgoing edge: if going through the current vertex is cheaper, update the neighbor.
Step-by-Step Walkthrough
Consider this weighted graph.
| Edge | Weight |
|---|---|
| A to B | 4 |
| A to C | 2 |
| C to B | 1 |
| B to D | 5 |
| C to D | 8 |
| D to E | 3 |
| B to E | 10 |
Start from A with distance zero.
- Pop A with distance zero. Relax B to four and C to two.
- Pop C with distance two. Improve B from four to three through C.
- Pop B with distance three. Improve D to eight and E to thirteen.
- Pop D with distance eight. Improve E to eleven.
- Pop E with distance eleven. Nothing left to improve.
Final distances: A zero, B three, C two, D eight, E eleven.
Python Implementation
import heapq
def dijkstra(graph, start):
dist = {start: 0}
parent = {start: None}
heap = [(0, start)]
visited = set()
while heap:
d, node = heapq.heappop(heap)
if node in visited:
continue
visited.add(node)
for neighbor, weight in graph[node]:
candidate = d + weight
if neighbor not in dist or candidate < dist[neighbor]:
dist[neighbor] = candidate
parent[neighbor] = node
heapq.heappush(heap, (candidate, neighbor))
return dist, parent
graph = {
"A": [("B", 4), ("C", 2)],
"B": [("A", 4), ("C", 1), ("D", 5), ("E", 10)],
"C": [("A", 2), ("B", 1), ("D", 8)],
"D": [("B", 5), ("C", 8), ("E", 3)],
"E": [("D", 3), ("B", 10)],
}
dist, parent = dijkstra(graph, "A")
print(dist)
Path Reconstruction
Parent pointers rebuild the route once distances are known.
def build_path(parent, target):
path = []
current = target
while current is not None:
path.append(current)
current = parent[current]
path.reverse()
return path
print(build_path(parent, "E"))
Complexity
With a binary heap priority queue the standard bound is:
| Component | Cost |
|---|---|
| Vertex extractions | O(V log V) |
| Edge relaxations | O(E log V) |
| Total with heap | O of the quantity E plus V, times log V |
| Space | O(V plus E) |
A Fibonacci heap can improve theory to O of E plus V log V, but binary heaps dominate real code for simplicity.
Common Pitfalls
- Negative weights break correctness
- Forgetting to skip stale heap entries wastes work
- Mixing directed and undirected edges changes results
- Floating point weights can introduce tiny precision issues
Dijkstra versus BFS versus Bellman-Ford
| Algorithm | Weights | Cost | Notes |
|---|---|---|---|
| BFS | Unit only | O(V plus E) | Fewest hops |
| Dijkstra | Non-negative | O of E plus V times log V | Fast weighted |
| Bellman-Ford | Allows negative | O(V times E) | Detects negative cycles |
Dijkstra Dry Run Checklist
Before coding Dijkstra in an interview, dry run a five-node graph on paper. Maintain three tables: finalized flag, current best distance, and parent. At each pop, write the new distance only when the candidate improves the stored value. Cross out stale heap entries instead of trusting them blindly.
# Helper to relax one edge in a dry run table
def relax(dist, a, b, w):
if a not in dist:
return
cand = dist[a] + w
if b not in dist or cand < dist[b]:
dist[b] = cand
return True
return False
dist = {"A": 0}
print(relax(dist, "A", "B", 4)) # True
print(dist)
Checklist before you claim correctness:
- Weights are non-negative
- Start distance is zero and others are unknown
- Pop skips already finalized vertices
- Relax uses strict improvement
- Parent updates only when distance improves
Run one negative-weight counterexample to explain why Bellman-Ford exists. Interviewers often probe that boundary next.
Key Takeaways
💡
- Dijkstra requires non-negative edge weights
- A min-priority queue always expands the closest unsettled vertex
- Relaxation updates distance and parent when a cheaper route appears
- Runtime with a binary heap is about O of E plus V times log V
- Reconstruct paths by walking parent pointers backward
Practice Questions
- Run Dijkstra by hand on a five-vertex graph and list distances after each pop.
- Why does a negative edge break Dijkstra after a node is finalized?
- Compare when to choose BFS instead of Dijkstra for a map problem.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions