Skip to content
Tactiverge

Path planning on grids

Find routes for a mobile robot on a grid map: breadth-first search for the fewest moves, Dijkstra's algorithm for the cheapest route, and A*, which uses a heuristic to search less.

Lesson 5 of 6 · 40 min · Self-paced · Free

Why path planning?

A delivery robot in a warehouse, a vacuum robot in a living room and a rover on rough ground all face the same question: how do I get from here to there without hitting anything? Before a robot can drive, something must turn a map and a goal into a sequence of moves. That is path planning.

A common, simple map is an occupancy grid: the world is divided into equal square cells, each marked free or blocked. You met grids as lists of lists in the lesson on lists and dictionaries. Here we use a list of strings, which is easier to read, and allow the robot to move one cell up, down, left or right at a time.

The map and some helpers

Save this as gridmap.py; the programs that follow import it. # is a wall, . is free floor, ~ is sand that the robot can cross but only slowly, S is the start and G the goal. Cells are identified by tuples (row, col) — a tuple is like a list that cannot be changed, and it can be used as a dictionary key.

# gridmap.py
GRID = [
    "............",
    ".##########.",
    "S....~~~...G",
    ".######.###.",
    "......#.....",
    "....#...#...",
]

def find(grid, symbol):
    """Return the (row, col) of the first cell containing symbol."""
    for r, row in enumerate(grid):
        if symbol in row:
            return (r, row.index(symbol))

def neighbours(grid, cell):
    """Cells up, down, left and right of cell that are inside the map and not walls."""
    r, c = cell
    result = []
    for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        nr, nc = r + dr, c + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#":
            result.append((nr, nc))
    return result

def trace_path(came_from, goal):
    """Follow came_from links back from goal to the start."""
    path = []
    cell = goal
    while cell is not None:
        path.append(cell)
        cell = came_from[cell]
    path.reverse()
    return path

def show(grid, path):
    """Print the map with the path drawn as * characters."""
    for r, row in enumerate(grid):
        print("".join("*" if (r, c) in path and ch in ".~" else ch for c, ch in enumerate(row)))

Breadth-first search

Breadth-first search (BFS) explores outwards from the start like a ripple on a pond: first every cell one move away, then every cell two moves away, and so on. The first time the ripple reaches the goal, it has found a route with the fewest moves.

BFS keeps a queue of cells waiting to be explored. New cells join at the back; the next cell to explore comes from the front, so cells are explored in order of distance. A dictionary came_from records, for each cell reached, which cell we came from. That serves two purposes: it tells us which cells we have already seen, so we never explore one twice, and it lets us trace the path backwards from the goal at the end.

from collections import deque
from gridmap import GRID, find, neighbours, trace_path, show

def bfs(grid, start, goal):
    came_from = {start: None}
    queue = deque([start])
    expanded = 0
    while queue:
        cell = queue.popleft()          # oldest cell first
        expanded += 1
        if cell == goal:
            return trace_path(came_from, goal), expanded
        for nxt in neighbours(grid, cell):
            if nxt not in came_from:    # not seen before
                came_from[nxt] = cell
                queue.append(nxt)
    return None, expanded               # the goal cannot be reached

start, goal = find(GRID, "S"), find(GRID, "G")
path, expanded = bfs(GRID, start, goal)
print(f"{len(path) - 1} moves, {expanded} cells expanded")
show(GRID, path)

Output:

11 moves, 41 cells expanded
............
.##########.
S**********G
.######.###.
......#.....
....#...#...

deque, from the standard collections module, is a list designed for fast adding and removing at both ends. BFS found the straight route along the middle row: 11 moves. "Expanded" counts the cells whose neighbours we examined, a fair measure of the work done.

But look at the route: it drives straight through three cells of sand. BFS treats every move as equal, so it cannot know that sand is slow.

Dijkstra's algorithm: the cheapest path

Suppose moving into a free cell costs 1 and moving into sand costs 5. The middle route costs 8 × 1 + 3 × 5 = 23. Is there something cheaper?

Dijkstra's algorithm generalises BFS to moves with different costs. Instead of exploring cells in order of number of moves, it always explores the cell with the lowest total cost so far. To pick that cell quickly it uses a priority queue: Python's heapq module keeps a list arranged so the smallest item can always be removed in O(log n) time.

A*: searching with a sense of direction

Dijkstra explores in every direction equally, including away from the goal. The A star algorithm, written A* for short, adds a heuristic: an estimate of the remaining cost to the goal. It explores cells in order of

priority = cost so far + estimated cost still to go

On a grid with up/down/left/right moves, a natural estimate is the Manhattan distance: the number of rows plus the number of columns between a cell and the goal. Because every move costs at least 1, this estimate can never be more than the true remaining cost. A heuristic with that property is called admissible, and it guarantees that A* still finds the cheapest path.

The two algorithms are so similar that one function can do both — Dijkstra is simply A* with an estimate of zero:

import heapq
from gridmap import GRID, find, neighbours, trace_path, show

def step_cost(grid, cell):
    return 5 if grid[cell[0]][cell[1]] == "~" else 1   # sand is slow

def manhattan(a, b):
    return abs(a[0] - b[0]) + abs(a[1] - b[1])

def plan(grid, start, goal, use_heuristic):
    came_from = {start: None}
    cost_so_far = {start: 0}
    frontier = [(0, start)]                  # (priority, cell)
    expanded = 0
    while frontier:
        _, cell = heapq.heappop(frontier)    # lowest priority first
        expanded += 1
        if cell == goal:
            return trace_path(came_from, goal), cost_so_far[goal], expanded
        for nxt in neighbours(grid, cell):
            new_cost = cost_so_far[cell] + step_cost(grid, nxt)
            if nxt not in cost_so_far or new_cost < cost_so_far[nxt]:
                cost_so_far[nxt] = new_cost
                came_from[nxt] = cell
                priority = new_cost
                if use_heuristic:
                    priority += manhattan(nxt, goal)
                heapq.heappush(frontier, (priority, nxt))
    return None, None, expanded

start, goal = find(GRID, "S"), find(GRID, "G")
for name, use_heuristic in [("Dijkstra", False), ("A*", True)]:
    path, cost, expanded = plan(GRID, start, goal, use_heuristic)
    print(f"{name}: {len(path) - 1} moves, cost {cost}, {expanded} cells expanded")
show(GRID, path)

Output:

Dijkstra: 15 moves, cost 15, 42 cells expanded
A*: 15 moves, cost 15, 22 cells expanded
************
*##########*
S....~~~...G
.######.###.
......#.....
....#...#...

Both algorithms chose the route around the top: 15 moves instead of 11, but a cost of 15 instead of 23. The shortest path and the cheapest path are different things, and the planner can only optimise what its costs describe.

Both found the same cost, but A* expanded 22 cells while Dijkstra expanded 42. The heuristic steered A* towards the goal, so it wasted less effort on cells in the bottom of the map. On large maps — a warehouse might be thousands of cells across — this saving is what makes planning fast enough to run while the robot moves.

The three algorithms side by side

  • BFS: explores in order of number of moves. Finds the fewest-move path. Uses a plain queue.
  • Dijkstra: explores in order of cost so far. Finds the cheapest path when costs differ. Uses a priority queue.
  • A star (A*): explores in order of cost so far plus an estimate of the cost to go. Finds the cheapest path, usually exploring far fewer cells, provided the estimate never overestimates.

If the heuristic overestimates — say you multiplied the Manhattan distance by 10 — A* becomes greedier and faster but may return a path that is not the cheapest. Sometimes that trade-off is acceptable; it should always be a deliberate choice.

From grid paths to real robots

A planned grid path is a starting point, not the end of the story:

  • Robot size: a robot is not a point. Planners usually inflate obstacles by the robot's radius, so a path through free cells keeps the whole body clear.
  • Resolution: big cells make planning fast but can close narrow gaps; small cells are accurate but give the planner more work.
  • Movement: real robots can move diagonally and turn smoothly. Grid paths are often smoothed afterwards.
  • Change: people and doors move. Robots replan as their sensors update the map, which is another reason planning speed matters.
  • Unreachable goals: if walls enclose the goal, the search runs out of cells and returns None. Code that uses the path must handle that case.

Recap

  • An occupancy grid divides the world into free and blocked cells; neighbours are the cells one move away.
  • BFS explores outward with a queue and finds the path with the fewest moves.
  • Dijkstra's algorithm uses a priority queue to find the cheapest path when moves have different costs.
  • A* adds an admissible heuristic, such as the Manhattan distance, to find the same cheapest path while exploring less.
  • A came_from dictionary both prevents revisiting cells and lets you rebuild the path.
  • Real planners also inflate obstacles, choose a resolution and replan as the world changes.

Knowledge check

Check your understanding

  1. 1. What does breadth-first search guarantee on a grid where every move costs the same?
  2. 2. Why did Dijkstra's algorithm choose a 15-move route when BFS found an 11-move one?
  3. 3. In A*, a cell's priority is…
  4. 4. A heuristic is 'admissible' if…
  5. 5. Why do planners often inflate obstacles on the map before planning?

Project

Project: a planner of your own

On paper. Draw a 6 × 8 grid with a start, a goal and a few walls. Run BFS by hand: write 0 in the start cell, 1 in every free neighbour, 2 in their unvisited free neighbours, and so on until you reach the goal. Then trace the path back by stepping to any neighbour with a number one smaller.

In Python. Copy gridmap.py and the two planners from this lesson, then:

  1. Design your own map of at least 10 × 15 cells, including a region of costly cells. Check that BFS, Dijkstra and A* behave as you expect, and record moves, cost and cells expanded for each.
  2. Make the goal unreachable by surrounding it with walls. Make sure your program prints a clear message instead of crashing.
  3. Multiply the heuristic by 3. Does A* still find the cheapest path? How many cells does it expand?
  4. Add diagonal moves with a cost of 1.4, and explain in a sentence why the Manhattan distance is no longer admissible for this case.

No hardware is required.

Deliverables

  • A photo or scan of your hand-worked BFS grid
  • A Python 3 program and a table comparing the three algorithms on your map
  • Short answers to steps 3 and 4

Go further

Path planning on grids — Computational Engineering — Tactiverge