Dijkstra's algorithm
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Find the cheapest route from one start vertex to every other vertex when no road has a negative cost. Watch Dijkstra's algorithm run on five vertices and seven one-way roads: offers (cost, vertex) slide along the roads, drop into a priority queue when they beat the best known cost, and leave it smallest first. Each vertex that comes out is final. The loop is nine lines of Python with heapq. The lessons "Priority queues and heapsort" and "Binary heaps: sift up and sift down" cover the heap, and "Greedy choices: the exchange argument and when greedy fails" covers the style of proof used here.
Cheapest routes from S
Five places joined by one-way roads. Each road has a cost, its weight, and no weight is negative. Question: what is the cheapest route from S to every other vertex? Adding up costs along a route gives its length.
a weighted directed graph, V = 5 vertices, E = 7 edges S → A weight 4 S → B weight 1 A → C weight 1 B → A weight 2 B → C weight 5 B → D weight 5 C → D weight 3 every weight ≥ 0 (Dijkstra needs this) goal: dist[v] = length of the cheapest route S → v
اقرأ الدرس خطوة بخطوة
Cheapest routes from S
Five places joined by one-way roads. Each road has a cost, its weight, and no weight is negative. Question: what is the cheapest route from S to every other vertex? Adding up costs along a route gives its length.
a weighted directed graph, V = 5 vertices, E = 7 edges S → A weight 4 S → B weight 1 A → C weight 1 B → A weight 2 B → C weight 5 B → D weight 5 C → D weight 3 every weight ≥ 0 (Dijkstra needs this) goal: dist[v] = length of the cheapest route S → vStart: S costs 0
dist holds the best cost found so far. Every vertex starts at infinity (∞, no route known yet) and S at 0. A priority queue (a min-heap) holds offers (cost, vertex) and always hands out the smallest. It starts with (0, S).
dist = {v: inf for v in graph} # math.inf start dist[S] = 0, push (0, S) dist S=0 A=∞ B=∞ C=∞ D=∞ queue (0, S) heappop always returns the smallest offerTake S, relax its roads
Pop the smallest offer, (0, S). Relax each road out of S: is 0 + weight cheaper than dist? A: 0 + 4 = 4 < ∞, so write 4 and push (4, A). B: 0 + 1 = 1, push (1, B).
pop (0, S) S is settled at 0 S→A 0 + 4 = 4 < ∞ dist[A] = 4, push (4, A) S→B 0 + 1 = 1 < ∞ dist[B] = 1, push (1, B) dist S=0 A=4 B=1 C=∞ D=∞ queue (1, B) (4, A)B is next, and final
The smallest offer is (1, B), so B is settled at 1. Through B, A costs 1 + 2 = 3, cheaper than 4: dist[A] becomes 3 and (3, A) is pushed. C and D get 6 each.
pop (1, B) B is settled at 1 B→A 1 + 2 = 3 < 4 dist[A] = 3, push (3, A) B→C 1 + 5 = 6 < ∞ dist[C] = 6, push (6, C) B→D 1 + 5 = 6 < ∞ dist[D] = 6, push (6, D) dist S=0 A=3 B=1 C=6 D=6 queue (3, A) (4, A) (6, C) (6, D) the old (4, A) stays in the queue: heapq cannot change itA settles at 3
Next comes (3, A). Its road to C costs 3 + 1 = 4, which beats 6. So dist[C] becomes 4 and (4, C) joins the queue. The route S, B, A, C is now the best known way to C.
pop (3, A) A is settled at 3 A→C 3 + 1 = 4 < 6 dist[C] = 4, push (4, C) dist S=0 A=3 B=1 C=4 D=6 queue (4, A) (4, C) (6, C) (6, D)Skip an old offer
Out comes (4, A), the old offer. A already costs 3, and 4 > 3, so line 5 skips it. Python’s heapq cannot lower an entry in place, so we push a new one and ignore stale ones. This is called lazy deletion.
pop (4, A) stale: 4 > dist[A] = 3, skip dist S=0 A=3 B=1 C=4 D=6 queue (4, C) (6, C) (6, D) ties: (4, A) comes before (4, C) because tuples compare the vertex nextNot every offer wins
Pop (4, C): C settles at 4. Its road to D offers 4 + 3 = 7. But dist[D] is already 6, and 7 is not less than 6, so nothing changes. The offer is dropped and never enters the queue.
pop (4, C) C is settled at 4 C→D 4 + 3 = 7 ≥ 6 no change, drop it dist S=0 A=3 B=1 C=4 D=6 queue (6, C) (6, D)Empty queue, done
(6, C) is stale, so it is skipped. (6, D) settles D at 6; D has no roads out. The queue is now empty, so the while loop ends. Every vertex holds its cheapest cost.
pop (6, C) stale: 6 > dist[C] = 4, skip pop (6, D) D is settled at 6 dist S=0 A=3 B=1 C=4 D=6 queue empty 7 pops, 2 of them staleThe shortest-path tree
Each final cost was set by one road; those roads form a tree. The cheapest way to C is S, B, A, C: 1 + 2 + 1 = 4, beating S, A, C at 5. Store each previous vertex to rebuild routes.
final dist and the road that set it S 0 source A 3 via B→A route S → B → A B 1 via S→B route S → B C 4 via A→C route S → B → A → C D 6 via B→D route S → B → D to keep routes: add prev[v] = u next to dist[v] = d + wWhy smallest-first is safe
When B left the queue at 1, every other route to B had to leave S through a vertex still in the queue, like A at 4 or more. Weights are never negative, so going on can only add. Nothing beats 1.
claim: when u is popped (not stale), dist[u] is final any other route S ⇝ u first leaves the settled set at some x x was still waiting, so its offer ≥ dist[u] (u was the smallest) the rest of the route has weight ≥ 0 so that route costs ≥ dist[u] a negative weight breaks the last line: use Bellman-Ford insteadHow much it costs
Each road is relaxed once, so there are at most E + 1 pushes and pops. Each takes O(log V) on a binary heap. Total: O((V + E) log V). Here: 7 relaxations, 7 pushes, 7 pops.
this run: V = 5, E = 7 relaxations 7 (one per edge) pushes 7 (the start + 6 improvements) pops 7 (5 settle, 2 stale) queue size ≤ E + 1, and log(E) ≤ 2 log(V) binary heap: O((V + E) log V) Fibonacci heap: O(E + V log V) (MIT 6.006)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01dist[v] is 9. You pop u with d = 4, and the edge u → v has weight 3. What happens?
Relaxing the edge: 4 + 3 = 7 is less than 9, so the cheaper cost is written down and a new offer (7, v) goes into the queue.
02In the lesson's run, why is (4, A) skipped when it leaves the queue?
B found a cheaper route to A (cost 3) and pushed (3, A). heapq cannot lower the old entry, so (4, A) stays in the queue and line 5 skips it when it comes out.
03Why can Dijkstra trust a vertex as soon as it leaves the queue with the smallest cost?
Any other route leaves the settled set through some waiting vertex, whose cost is already at least the smallest offer. With no negative weights the rest of the route cannot bring the total back down.
04What goes wrong with a negative edge weight?
The proof needs weights of 0 or more. With a negative road, a later vertex can make an already settled one cheaper. Use Bellman-Ford for graphs with negative weights.
05With a binary heap, what is the running time of Dijkstra's algorithm on V vertices and E edges?
Each edge is relaxed once, so there are O(E) pushes and pops, each costing O(log V) on a binary heap, plus O(V) setup.
المسرد
- Weighted graph
- A graph where each edge has a number, its weight or cost. Here the edges are one-way roads.
- Shortest path
- The route between two vertices whose weights add up to the smallest total.
- dist[v]
- The cheapest cost from the start to v found so far. It starts at infinity and only goes down.
- Relax an edge
- For an edge u → v with weight w, check whether dist[u] + w beats dist[v]; if it does, write the new value down.
- Priority queue
- A queue that always hands out its smallest item first. Python's heapq builds one on a list.
- Settled vertex
- A vertex that has left the queue with its smallest offer. Its cost is final.
- Stale entry
- An old, larger offer for a vertex that already has a cheaper cost. It is skipped when it comes out of the queue.
- Shortest-path tree
- The edges that set each vertex's final cost. Following them back from any vertex gives its cheapest route.
الملاحظات والمصادر
- The figure lines the queue up smallest first so it is easy to read. Python’s heapq really keeps the list in heap order, where only pq[0] is guaranteed to be the smallest; heappop returns the same offers in the same order.
- Textbook versions (MIT 6.006, CLRS, Sedgewick and Wayne’s IndexMinPQ) use a decrease-key operation instead of stale entries, so the queue holds at most V items. The lazy version used here is the one the Python heapq documentation suggests; it has the same O((V + E) log V) bound.
- With a negative weight the proof fails: a road out of a later vertex could make an already settled vertex cheaper. Sedgewick and Wayne note that this version “may yield incorrect results” then; Bellman-Ford handles negative weights.
- The code is real Python 3. With the graph above it prints {'S': 0, 'A': 3, 'B': 1, 'C': 4, 'D': 6}. inf is math.inf, a float infinity, so d + w < inf is true for any real number.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 13: Dijkstra's Algorithm
- Sedgewick and Wayne, Algorithms 4th ed., §4.4 Shortest Paths
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §22.3 Dijkstra's algorithm
- Python standard library: heapq, heap queue algorithm
- Python standard library: math.inf
اختبار يتاح بعد الخطوة الأخيرة.