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.
Comments