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:
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.
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
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
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:
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.
Press Run Tests or ββ© to check your solution.