Skip to content

Featured article for the topic Shortest paths · picked by the needcode team

Dijkstra without the fear

Meera IyerFeatured AuthorPosted · 1 min read

Dijkstra is BFS with a priority queue. If you can write BFS, you can write Dijkstra.

import heapq

def dijkstra(graph, src):
    dist = {src: 0}
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist.get(u, float("inf")):
            continue  # stale entry
        for v, w in graph[u]:
            nd = d + w
            if nd < dist.get(v, float("inf")):
                dist[v] = nd
                heapq.heappush(heap, (nd, v))
    return dist

When to use which#

  • Unweighted edges: plain BFS.
  • Non-negative weights: Dijkstra, O((V + E) log V).
  • Negative weights: Bellman-Ford.
Text by Meera Iyer, licensed under CC BY-SA 4.0. You may share and adapt it with credit to the author, under the same licence.

Other approaches to Shortest paths

Submit your approach

No other approaches yet. Think you can explain it differently? Write one.

Comments

Loading comments…