Neighbors

Step 1: Neighbors

Every grid algorithm needs one primitive: given a cell, which cells are adjacent to it?

Write neighbors(grid, r, c) that returns a list of the in-bounds 4-directional neighbor coordinates of cell (r, c), as (row, col) tuples.

Explore directions in this fixed order and skip any that fall outside the grid:

  1. up: (r - 1, c)
  2. down: (r + 1, c)
  3. left: (r, c - 1)
  4. right: (r, c + 1)

The grid is a list of lists (a rectangular matrix). A corner cell has 2 neighbors; a center cell has 4. Keeping the order fixed makes every later search deterministic.

Hints
Starter code
def neighbors(grid, r, c):
    """Return in-bounds 4-directional neighbor coords: up, down, left, right."""
    # TODO: check up, down, left, right in that order; keep only in-bounds cells
    pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.