A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Dijkstra's Algorithm

Graduate Depth 94 in the knowledge graph ☐ I know this ☆ Set as goal
29topics build on this
601prerequisites beneath it
See this on the map →
Breadth-First Search (BFS)Graph Representations: Adjacency List vs. Adjacency Matrix+7 more→→A* Search AlgorithmBellman-Ford Algorithm+2 more
shortest-path Dijkstra weighted-graph greedy

Core Idea

Dijkstra's algorithm finds the shortest path from a source vertex to all other vertices in a weighted graph with non-negative edge weights. It uses a greedy strategy with a priority queue: always extend the shortest known tentative path first. With a binary heap, the algorithm runs in O((V + E) log V). The algorithm maintains a distance array and relaxes edges by updating distances when a shorter path is discovered. It is the workhorse of navigation systems, network routing, and game AI pathfinding.

How It's Best Learned

Implement Dijkstra's using Python's heapq module. Trace through a small weighted graph manually, tracking the priority queue state and distance table at each step. Add path reconstruction using a previous-node array.

Common Misconceptions

Explainer

You already know BFS explores a graph level by level, finding the shortest path in terms of number of edges. Now suppose every edge has a different cost — a road map with varying distances, a network with different latencies. "Fewest hops" is no longer the right objective; you want "minimum total cost." Dijkstra's algorithm solves exactly this, and it extends BFS in the most natural way possible: replace the FIFO queue with a min-heap (priority queue) ordered by tentative path cost.

The algorithm maintains a distance table: `dist[v]` = the shortest path cost found so far from the source to vertex `v`. Initially, `dist[source] = 0` and all other distances are infinity. The priority queue holds `(cost, vertex)` pairs. At each step, you extract the vertex with the lowest tentative cost, then examine every edge from that vertex. For each neighbor, you compute the cost of reaching it through the current vertex (`dist[current] + edge_weight`). If this cost is less than the neighbor's current `dist` value, you relax the edge — update `dist[neighbor]` and push the improved `(new_cost, neighbor)` into the priority queue. Vertices that have been extracted from the queue are "finalized" and never revisited.

The algorithm's correctness depends entirely on one invariant: once a vertex is extracted from the min-heap, its distance is final and optimal. This is true only if all edge weights are non-negative. Why? When you extract the minimum-cost vertex, every path to it that hasn't been explored yet must pass through an unvisited vertex with equal or higher tentative cost. Because all remaining edges are non-negative, those unexplored paths can only get longer or stay the same — they can never sneak in and provide a shorter route to the already-finalized vertex. A single negative edge destroys this guarantee, which is why Dijkstra's fails in that case (Bellman-Ford handles negative weights instead).

The runtime is O((V + E) log V) with a binary heap. You perform V extractions (each O(log V)) and at most E relaxations (each involving a push or decrease-key, O(log V)). For dense graphs where E ≈ V², this is O(V² log V), actually worse than the naive O(V²) array implementation. Dijkstra's with a heap wins on sparse graphs — exactly the kind found in road networks and game maps, which is why it dominates in practice.

To reconstruct the actual shortest path (not just the distance), maintain a `prev` array alongside `dist`: when you relax an edge to neighbor `v` through vertex `u`, record `prev[v] = u`. After the algorithm finishes, walk backward from the destination following the `prev` pointers to recover the full path. This adds no asymptotic cost and turns Dijkstra's from a "find the cost" tool into a "find the route" tool.

Practice Questions 3 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Conditional Statements → Defining and Calling Functions → Functions: Decomposing Problems → Function Parameters and Argument Passing → Return Values → Variable Scope → Introduction to Classes → Objects and Instances → Methods and Attributes → Algorithm Design Basics → Tree Structure and Node Properties → Binary Trees → Tree Traversals → Depth-First Search (DFS) → Depth-First Search: Implementation and Applications → Topological Sort → Dynamic Programming → Longest Common Subsequence (LCS) Problem → Edit Distance: Levenshtein Distance and DP → 0/1 Knapsack Problem: Bounded Capacity DP → Greedy Algorithms → Activity Selection Problem Using Greedy Algorithms → Dijkstra's Algorithm

Longest path: 95 steps · 601 total prerequisite topics

Prerequisites (9)

Leads To (4)