Skip to main content

DSAPath14 minintermediate

Dijkstra vs A*

Dijkstra searches by known cost from the source; A* adds a heuristic estimate to guide search toward a target.

DifficultyIntermediate
TierTier 1
ModuleComparisons
LanguagesPython

Why This Matters

Dijkstra is a general shortest-path algorithm for nonnegative weights. A* is what you reach for when there is one target and a useful heuristic can point the search in the right direction.

Decision Rule

Use Dijkstra when you need distances to many vertices or have no reliable heuristic. Use A* when you need a path to a specific target and can define an admissible heuristic that never overestimates remaining cost.

Comparison Table

FeatureDijkstraA*
Priority valueg(n) known distanceg(n) + h(n) known plus estimated remaining distance
Targetone source to many nodesone source to one target
Heuristic needednoyes
Correctness conditionnonnegative weightsnonnegative weights plus suitable heuristic
Common userouting tables, all reachable distancesmaps, game pathfinding, grid navigation

Worked Example

On a grid, Dijkstra expands outward in all directions by current distance. A* with Manhattan distance tends to expand toward the goal because cells closer to the goal receive a lower g + h score.

If the heuristic overestimates, A* may skip the actual shortest route. If the heuristic is zero everywhere, A* becomes Dijkstra.

Common Mistakes

MistakeCorrection
Using any heuristic and assuming optimality.The heuristic must be admissible for the usual shortest-path guarantee.
Using A* for all-pairs or all-destination distances.Dijkstra or Floyd-Warshall may fit better.
Forgetting that A* still uses a priority queue.The priority is g + h, not just h.

Diagnostic Questions

QuestionAnswer signal
What is g(n) in A*?Known cost from start to node n.
What happens when h(n) = 0 for every node?A* behaves like Dijkstra.
Why can a bad heuristic break A*?It can overestimate and cause the algorithm to prefer a nonoptimal route.

Exercises

  • Beginner: Choose Dijkstra or A* for all distances from one router.
  • Beginner: Choose Dijkstra or A* for one path in a grid maze.
  • Beginner: Define Manhattan distance on a four-neighbor grid.
  • Intermediate: Implement A* on a small grid with blocked cells.
  • Intermediate: Compare nodes expanded by Dijkstra and A* on the same maze.
  • Challenge: Explain admissible versus consistent heuristics with a counterexample.

References