ENع
→Dijkstra
الدرس 33 · Shortest paths and spanning trees

Dijkstra's algorithm

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة11 خطوة5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 33 · تفاعلي
01 / 11

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. Start: 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 offer
  3. Take 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)
  4. 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 it
  5. A 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)
  6. 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 next
  7. Not 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)
  8. 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 stale
  9. The 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 + w
  10. Why 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 instead
  11. How 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)

اختبار يتاح بعد الخطوة الأخيرة.