Skip to content
CodeItRaw
Path

Grids and mazes are graphs: reachability, connected components, BFS and shortest paths.

Key ideas

  • A grid is a graph: each cell is a node, its neighbours are up, down, left and right.
  • BFS (with a queue) finds shortest paths layer by layer; DFS (a stack or recursion) walks connected regions.
  • Keep visited cells in a set, or you will loop forever.

Pattern

from collections import deque
seen = {start}
queue = deque([start])
while queue:
    x, y = queue.popleft()
    for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
        if open_cell(nx, ny) and (nx, ny) not in seen:
            seen.add((nx, ny))
            queue.append((nx, ny))

Finish these first:Stacks & Queues

Lessons

Each lesson explains one idea from zero and ends with a few tasks. Lessons open in order; the explanation can be read at any time.

  1. 01

    Graphs: places and ways between them

    0/2 tasks

  2. 02

    Mark what you have seen

    0/3 tasks

  3. 03

    Counting the pieces

    0/3 tasks

  4. 04

    The shortest way: breadth-first search

    0/2 tasks

Boss

  • 05

    Shortest Route

    Function

  • The boss opens when every lesson of the topic is finished. Solve it too and the topic is complete, and the topics after it open.