dijkstra_editorial

Dijkstra's Algorithm

Cho do thi co huong co trong so G=(V,E)G = (V, E) voi nn dinh va mm canh, moi canh (u,v)(u, v) co trong so w(u,v)0w(u, v) \geq 0. Cho dinh nguon ss, tim duong di ngan nhat tu ss toi tat ca cac dinh con lai. Goi d[v]d[v] la do dai duong di ngan nhat tu ss toi vv.

Cong thuc relax (noi long) la co so cua thuat toan: \[ d[v] = \min\bigl(d[v],\; d[u] + w(u, v)\bigr) \] Neu duong di qua uu roi toi vv ngan hon duong di hien tai toi vv, ta cap nhat d[v]d[v].

Input Graph

Arrowhead (forward)Arrowhead (reverse)Edge from node A to node B4Edge from node A to node C2Edge from node B to node C1Edge from node B to node D7Edge from node C to node D3Edge from node C to node E5Edge from node D to node E1ABCDE

Algorithm

Thuat toan Dijkstra hoat dong theo nguyen tac tham lam (greedy): tai moi buoc, chon dinh uu chua xu ly co d[u]d[u] nho nhat, danh dau uu la da xu ly (settled), roi relax tat ca canh ke (u,v)(u, v). Dung priority queue (hang doi uu tien) de chon uu hieu qua trong O(logV)O(\log V). Dieu kien: trong so canh phai khong am (w0w \geq 0).

Step 1 / 13

Complexity

Voi priority queue (binary heap), do phuc tap cua Dijkstra la O((V+E)logV)O((V + E) \log V): moi dinh duoc push/pop dung mot lan (O(VlogV)O(V \log V)), moi canh duoc relax dung mot lan voi thao tac decrease-key (O(ElogV)O(E \log V)). Neu dung Fibonacci heap, do phuc tap giam xuong O(VlogV+E)O(V \log V + E). Luu y: Dijkstra chi dung khi trong so canh khong am. Neu co canh am, dung Bellman-Ford (O(VE)O(VE)) hoac SPFA.

Implementation

import heapq
from math import inf

def dijkstra(adj, src):
    n = len(adj)
    dist = [inf] * n
    dist[src] = 0
    pq = [(0, src)]

    while pq:
        d_u, u = heapq.heappop(pq)
        if d_u > dist[u]:
            continue
        for v, w in adj[u]:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                heapq.heappush(pq, (dist[v], v))

    return dist