Drill

ProblemsPython › games

Count neighbouring live cells

mediumgamesPython

In a grid-based game, count how many of the eight surrounding cells around a given position hold a value of 1.

board_neighbours(grid: list<list<int>>, row: int, col: int) → int

Solve it in the editor →

Where you start

def board_neighbours(grid: list[list[int]], row: int, col: int) -> int:
    

Worked examples

CallResult
board_neighbours([[1, 1, 1], [1, 0, 1], [1, 1, 1]], 1, 1)8
board_neighbours([[0, 0, 0], [0, 1, 0], [0, 0, 0]], 1, 1)0
board_neighbours([[1, 1], [1, 1]], 0, 0)3
board_neighbours([[1, 0, 1], [0, 1, 0], [1, 0, 1]], 1, 1)4

Hint

Loop over offsets from -1 to +1 in both axes, skip (0,0), and bounds-check each neighbour.

Reference solution in Python
def board_neighbours(grid: list[list[int]], row: int, col: int) -> int:
    rows = len(grid)
    cols = len(grid[0])
    count = 0
    for dr in range(-1, 2):
        for dc in range(-1, 2):
            if dr == 0 and dc == 0:
                continue
            r, c = row + dr, col + dc
            if 0 <= r < rows and 0 <= c < cols and grid[r][c] == 1:
                count += 1
    return count

The same problem in another language

More games problems in Python