Skip to content
Tactiverge

School/○ Innovator/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

1.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.

  • ◇ Extend BFS to Dijkstra's algorithm using a priority queue (heapq) and per-cell costs.
  • ◇ Compare BFS and Dijkstra on the same maps by path length, path cost and cells expanded.
  • ◇ Structure the planner as modules with a map class and tests with known answers.

2.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?

Loading the interactive…

Can't use the interactive? Read a description instead

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.

3.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1

A path enters cells with costs 1, 1, 5, 5, 1, 1 (the start cell is free). What is its total cost?

Practice 2

pq holds (7, A), (3, B), (5, C) via heapq. What does heapq.heappop(pq) return?

4.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.

5.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

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.

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

  • Dijkstra is just a slower BFS.
    ✓ It solves a different problem: cheapest route under varying costs. On uniform costs it agrees with BFS.
  • The fewest-moves path is the best path.
    ✓ Best depends on the cost you care about: energy, time, risk. Put that cost in the map.

6.Watch

→ 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.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

The video is optional: everything you need is also in the lesson text and the interactive.

7.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 3

On a map where every free cell costs 1, how do BFS and Dijkstra compare?

Practice 4 · a fresh version every time

An editor keeps an undo stack of waypoint ids: s = []; s.append(38); s.append(23); s.append(27); s.pop(); s.append(33); s.pop(); s.append(3); s.pop(). What value does the final s.pop() return?

Practice 5

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

8.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?

Guess first. Being wrong here is how the surprise works.

9.Reflect

10.Go further

Concepts: Path planning and search · Algorithms, searching and complexity · Classes and objects