TactivergeLite

Lite / Intelligent Robotic Systems / Week 9

Project: plan a path that counts the cost

BFS finds the fewest moves, straight through the mud. Your rover's battery would rather go round. How does the planner learn to care?

About 50 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

This is the term project: 'plan a path, measure the cost'. You'll combine everything from this term: modules, a map class, a queue and a priority queue, dictionaries, tests and complexity. First, the planner itself.

Predict

A straight route crosses 3 rough cells (cost 9 each) then 1 floor cell; a detour has 6 floor cells (cost 1 each). Which does Dijkstra choose?

  1. The straight route: fewer moves
  2. The detour: total cost 6 instead of 28
  3. Whichever it finds first
Guess first, then reveal

The detour. Dijkstra minimises the total cost of the cells entered: 6 × 1 = 6 beats 3 × 9 + 1 = 28. BFS would take the straight route because it only counts moves.

Discover

Run BFS, then Dijkstra, on the default map: compare moves, cost and cells expanded. Then paint a strip of rough ground across the direct route and run both again. Can you build a map where Dijkstra takes twice as many moves as BFS but costs less?

What the interactive shows (text version)

The planner shows the same map under BFS and Dijkstra. BFS finds the fewest moves and may cross the rough (cost 5) patch; Dijkstra finds the lowest total cost and may detour round it, expanding cells in order of cost so far. The readout reports moves, total cost and cells expanded for each.

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: Watch how the algorithm always picks the cheapest unfinished node next, and why that guarantees the cheapest route.

Works Dijkstra's shortest-path algorithm by hand on a small map, the improvement on breadth-first search in the term project.

“Dijkstra's Algorithm - Computerphile” by Computerphile (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

Understand

From queue to priority queue

BFS takes the oldest cell; Dijkstra takes the cheapest-so-far cell. Python's heapq keeps a list as a priority queue: heappush(pq, (cost, cell)) and heappop(pq) returns the smallest cost in O(log n). When a cell is popped, its cost is final.

Relax the neighbours

For each neighbour, the candidate cost is cost[cell] + step_cost(neighbour). If that beats the best known cost, record it, set came_from, and push it. Old, worse entries may stay in the heap; skip them when popped if the cell is already finished.

Project structure

grid.py (a GridMap class with neighbours and cost), planners.py (bfs and dijkstra as functions taking a map), experiment.py (timing and counting), test_planners.py (corridor, detour, unreachable goal, uniform-cost map where both agree). Each planner returns the path, its cost and the number of cells expanded.

Explain it another way

Intuitive

Dijkstra is like water flowing through ground of varying difficulty: it always advances where progress is cheapest, so the first time it reaches the goal it has found the cheapest way there.

Technical

With a binary heap, Dijkstra runs in O((V + E) log V). On a grid E ≈ 4V, so O(V log V). It needs non-negative costs. On a uniform-cost grid it expands cells in the same order of distance as BFS but pays a log factor for the heap.

Mathematical

Invariant: when a cell is popped, its recorded cost equals the true cheapest cost, because every other frontier route already costs at least as much and costs never decrease along a path (all step costs ≥ 0).

Applied

Ground robots plan on cost maps where each cell's cost reflects slope, roughness or distance from obstacles. Dijkstra and its goal-directed variant A* are standard choices for that kind of planning.

Worked example 1

Dijkstra on a cost grid (0 = wall), returning path, cost and cells expanded.

import heapq


def dijkstra(costs, start, goal):
    """costs: list of rows of ints (0 = wall, else cost of entering). Returns (path, cost, expanded)."""
    h, w = len(costs), len(costs[0])
    best = {start: 0}
    came_from = {start: None}
    done = set()
    pq = [(0, start)]
    while pq:
        c, cell = heapq.heappop(pq)
        if cell in done:
            continue                       # a stale, more expensive entry
        done.add(cell)
        if cell == goal:
            path = []
            while cell is not None:
                path.append(cell)
                cell = came_from[cell]
            return path[::-1], c, len(done)
        r, col = cell
        for n in [(r - 1, col), (r, col + 1), (r + 1, col), (r, col - 1)]:
            nr, nc = n
            if 0 <= nr < h and 0 <= nc < w and costs[nr][nc] > 0 and n not in done:
                new = c + costs[nr][nc]
                if new < best.get(n, float("inf")):
                    best[n] = new
                    came_from[n] = cell
                    heapq.heappush(pq, (new, n))
    return [], float("inf"), len(done)


terrain = [[1, 1, 1, 1, 1],
           [1, 9, 9, 9, 1],
           [1, 9, 9, 9, 1],
           [1, 1, 1, 1, 1]]
path, cost, expanded = dijkstra(terrain, (1, 0), (1, 4))
print(len(path) - 1, cost)    # 6 6   (BFS would take 4 moves costing 28)

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

Practice 2. pq holds (7, A), (3, B), (5, C) via heapq. What does heapq.heappop(pq) return?
Practice 3. On a map where every free cell costs 1, how do BFS and Dijkstra compare?

Practice 5. Why must Dijkstra's step costs be non-negative?

Apply it

Term project, part 1. Build the planner package (grid.py, planners.py, tests). Both planners must take a GridMap and return (path, cost, expanded). Tests must include a corridor, a forced detour, an unreachable goal, and a map where Dijkstra's path is longer but cheaper than BFS's, each with an answer worked by hand.

Reflect

What cost would you put on each cell for a real rover, and where would those numbers come from?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← Mean, median and spread: summarising a log honestlyProject: measure the cost, plot it honestly →