Count neighbouring live cells
In a grid-based game, count how many of the eight surrounding cells around a given position hold a value of 1.
- Check all eight directions: orthogonal and diagonal.
- Cells outside the grid boundary are ignored.
- The cell at the given position itself is never counted.
board_neighbours(grid: list<list<int>>, row: int, col: int) → int
Where you start
def board_neighbours(grid: list[list[int]], row: int, col: int) -> int:
Worked examples
| Call | Result |
|---|---|
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