Skip to content
CodeItRaw
Graphs

Lesson 2/4

Because a graph can have loops, if you do not remember where you have been you go back and forth between the same two nodes for ever. The cure is a seen set: you queue a node only if you have not seen it before.

def reachable(grid, r, c, seen):
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])):
return
if grid[r][c] == "#" or (r, c) in seen:
return
seen.add((r, c))
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
reachable(grid, r + dr, c + dc, seen)
The same walk on a grid, with recursion: first "am I inside the grid", then "is it a wall, have I been here"; if neither, mark the cell and go to the four neighbours. Keeping the four directions in a list is shorter and safer than writing four separate lines.

"Is there a way from A to B?" is this walk itself: start at A, and if B is among the seen when the walk ends, there is a way. Extra links like teleport pads only add one more edge to the neighbour list; the walk stays the same.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Is There a Way?

    Function

  2. 02

    Reachable Nodes

    Code reading · Bug Hunt

  3. 03

    Pad Network

    Infiltration

If you would rather not wait for the order, every problem is open without locks: Problem list