Interactive demo

Dijkstra's Algorithm

Edsger W. Dijkstra published his algorithm in 1959. It always continues from the cheapest cell found so far, so its frontier grows by cost instead of by steps, and it is guaranteed to find the cheapest path.

Your browser does not support the HTML5 canvas tag.

Draw walls or mud on the grid and drag the start and the goal. Once a search is finished, every change is searched again right away. Paint a wide band of mud: the frontier slows down inside it, and the path goes around if that is cheaper. Every step into or out of mud costs more.

Playback

Expanded
–
Frontier (max.)
–
Path cost
–

Press Play or Next Step to start the search.

Grid

Options

Legend

  • Start (drag to move)
  • Goal (drag to move)
  • Wall
  • Mud
  • Frontier (open list)
  • Visited (closed list)
  • Expanded right now
  • Path

Properties

Optimal

Yes

Cells are finished in the order of their cost, so the goal is reached by the cheapest path.

Weighted cells

Yes

Handles any costs that are not negative, like the mud here.

Heuristic

No

No sense of direction: it searches as much away from the goal as towards it.

Any angle

No

Moves from cell to cell, straight or diagonally.

All pathfinding algorithms compared

AlgorithmOptimalWeighted cellsHeuristicAny angle
Breadth-First SearchWithout mud and diagonalsNoNoNo
Depth-First SearchNoNoNoNo
Dijkstra's Algorithm this pageYesYesNoNo
Bidirectional SearchYesYesNoNo
Greedy Best-First SearchNoNoYesNo
A* SearchWith weight 1 and an admissible heuristicYesYesNo
Jump Point SearchWithout mudNoYesNo
Theta*NoShortcuts over open ground onlyYesYes

1. A priority queue

  1. Give the start the cost 0 and every other cell an infinite cost.
  2. Take the cell with the lowest cost out of the priority queue. Its cost is now final.
  3. For every neighbor, check whether the way through this cell is cheaper than the best one known. If so, update its cost and parent.
  4. Repeat until the goal is taken out.

2. Costs of the steps

A step costs its length (1, or √2 diagonally) times the average weight of the two cells: 1 on open ground, 5 in mud. Dijkstra's algorithm works with any costs that are not negative.

3. Where it is used

Route planners, network routing protocols such as OSPF and many games use Dijkstra's algorithm or its descendants. It is also the base of A*, which adds an estimate of the remaining distance.

Credits