Dijkstra's Algorithm
Dijkstra's Algorithm
Dijkstra's algorithm finds the cheapest path (minimum total edge weight) from a source to a destination on a weighted graph. It always expands the unvisited node with the lowest total cost so far, guaranteeing optimality.
How It Works
- Set the cost to reach the start node as 0, all others as infinity
- Pick the unvisited node with the lowest cost (use a priority queue)
- For each neighbor, calculate the cost through the current node
- If this new cost is cheaper than the known cost, update it
- Mark the current node as visited
- Repeat until the goal is visited or all reachable nodes are processed
Code Snippet
Uses the WeightedGraph class from the Graphs and Weighted Graphs article:
def dijkstra(graph, start_node: int, goal_node: int) -> tuple[list[int], int]:
"""Find cheapest path from start to goal on a weighted graph.
Returns (path, total_cost)."""
num_nodes = graph.num_nodes
cost_to_reach = [float('inf')] * num_nodes
parent_of = [-1] * num_nodes
visited = [False] * num_nodes
cost_to_reach[start_node] = 0
frontier = [(0, start_node)] # (cost, node) pairs
while frontier:
# Pick the unvisited node with lowest cost
frontier.sort()
current_cost, current_node = frontier.pop(0)
if visited[current_node]:
continue
visited[current_node] = True
if current_node == goal_node:
break
for neighbor_node, edge_weight in graph.get_neighbors(current_node):
if visited[neighbor_node]:
continue
new_cost = current_cost + edge_weight
if new_cost < cost_to_reach[neighbor_node]:
cost_to_reach[neighbor_node] = new_cost
parent_of[neighbor_node] = current_node
frontier.append((new_cost, neighbor_node))
# Reconstruct path
path = []
node = goal_node
while node != -1:
path.append(node)
node = parent_of[node]
path.reverse()
total_cost = cost_to_reach[goal_node]
return path, total_cost
Why Dijkstra is Optimal
When Dijkstra visits a node, it has found the cheapest possible path to that node. This is because it always processes the lowest-cost node next — any unprocessed node has equal or higher cost, so it cannot provide a shortcut.
Requirement: All edge weights must be non-negative. Negative weights can create cheaper paths through already-visited nodes, breaking the guarantee.
Dijkstra vs BFS
| Property | BFS | Dijkstra |
|---|---|---|
| Graph type | Unweighted | Weighted (non-negative) |
| Optimizes | Fewest hops | Lowest total cost |
| Data structure | Queue | Priority queue |
| On unweighted graph | Optimal | Same result, more overhead |
On an unweighted graph (all weights = 1), Dijkstra degenerates to BFS. Use BFS when weights are uniform.
Time Complexity
- With a simple list as priority queue: O(V^2)
- With a binary heap: O((V + E) log V)
- With a Fibonacci heap: O(V log V + E) — theoretical best
For most practical cases, a binary heap is the right choice.
When to Use Dijkstra
- Finding cheapest path on weighted graphs with non-negative edges
- GPS/navigation (road network with distances or travel times)
- Network routing (minimizing latency or cost)
- Any "minimum cost path" problem where you don't know the goal's position relative to the start