Dijkstra's Algorithm

Expands the closest unvisited node by total cost, guaranteeing the lowest-cost path when all weights are non-negative.

Optimal:YesWeighted:Yes
Complexity
Best
O((V+E) log V)
Average
O((V+E) log V)
Worst
O((V+E) log V)
Space
O(V)
When to use: Best when moves have different non-negative costs (weighted grids).Finds the lowest-cost path (non-negative weights)Slower than BFS on unweighted grids
Pseudocode
dist[start] ← 0
pq ← [(0, start)]
parent[start] ← null
while pq not empty:
v ← extract_min(pq)
for each neighbor u of v:
newDist ← dist[v] + w(v,u)
if newDist < dist[u]:
dist[u] ← newDist; parent[u] ← v;
parent[u] ← v; push pq
if goal extracted: reconstruct path
Waiting to start…
2
7
2
3
6
4
6
8
8
3
8
8
5
7
9
4