science tinker

Pathfinding visualiser: BFS, DFS, Dijkstra and A*

Drag on the grid to draw walls (or mud, which costs 5 to cross). Drag S and G to move the start and goal. Choose an algorithm and press Find path: light blue squares show the order it explores, and yellow is the path it finds.

Graphs and grids

A map can be turned into a graph: points (nodes) joined by connections (edges), each with a cost. Here every square is a node joined to its neighbours above, below, left and right. Sat-navs, games and network routers all solve the same problem: find a good path from A to B.

Breadth-first and depth-first search

BFS explores in rings: every square 1 step away, then every square 2 steps away, and so on, using a queue. It always finds a path with the fewest steps, but treats every step as costing the same. DFS uses a stack: it follows one route as far as it can, then backs up. It is good for exploring everything (and for making mazes), but the path it finds is often long.

Dijkstra’s algorithm

Dijkstra’s algorithm always expands the square with the lowest total cost so far. When it reaches the goal, no cheaper path can exist. With mud on the grid, it happily takes a longer route round the mud if that costs less overall. It is used for routing on the internet and in maps.

A*

A* adds a guess of how far is left (here the Manhattan distance: steps across plus steps down) to the cost so far. Squares that seem to lead towards the goal are explored first, so it usually checks far fewer squares than Dijkstra and still finds the cheapest path, as long as the guess never overestimates. Video game characters find their way with A*.

See how quickly the work grows on the Big O page, and drive a line-following robot in the microcontroller simulator.

Questions students ask

What is the difference between BFS and DFS?

Breadth-first search (BFS) explores all squares one step away, then two steps, using a queue, so it finds the path with the fewest steps; depth-first search (DFS) follows one route as far as possible using a stack, so its path is often longer.

Why is A* faster than Dijkstra’s algorithm?

A* is usually faster than Dijkstra’s algorithm because it adds an estimate of the remaining distance to each square’s cost, so it explores squares that lead towards the goal first instead of spreading out in every direction.

Does Dijkstra’s algorithm always find the shortest path?

Dijkstra’s algorithm always finds the lowest-cost path as long as no edge has a negative cost.

Check yourself

3 quick questions. Tap an answer to see if you are right.

1. Which algorithm always finds the path with the fewest steps on an unweighted grid?

2. What does A* add to Dijkstra’s algorithm?

3. Dijkstra’s algorithm can fail when…

Related

More computer science

Know someone who needs this?

It’s free for every student. Send it to your class group chat.

Updated · Free, no sign-up ·

Connected tools

The same idea from another angle, across the site.