shortest-path

what

  • a graph search algorithm that finds the shortest path between 2 vertices
  • only work with non-negative edge weights

idea

  • use a greedy strategy:
    • maintain the set of vertices whose shortest distance from the source is known
    • at each step, add the closest vertex to the set

implementation

  1. Initialization:
    • Set the distance from source vertex to itself as 0 and to other vertices as
    • Use a priority queue to process vertices based on their shortest distance
  2. Relaxation:
    • Get the closest vertex in the priority queue and add it to the set
    • For each of ‘s neighbouring vertex , if the path is shorter than the current path , update the shortest path and add to the queue
from math import inf
from heapq import heappush, heappop
def dijkstra(root):
    h = [(0, root)]
    dp = [inf] * n
    
    while h:
        d, u = heappop(h)
        if d > dp[u]:
            continue
        
        dp[u] = d
        for v, w in neighbours[u]:
            if dp[u] + w < dp[v]:
                dp[v] = dp[u] + w
                heappush(h, (dp[v], v))
    
    return dp

complexity

  • Time:
    • because we have to process all the edges
    • because the priority queue has maximum size of
      • This can be improved to using an augmented priority queue which uses a dict to store the index of each vertex in the heap, allowing removal by value.
  • Space:

note

  • Time complexity can be improved to using fibonacci heap