Problems › TypeScript › games
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.
boardNeighbours(grid: list<list<int>>, row: int, col: int) → int
Where you start
function boardNeighbours(grid: number[][], row: number, col: number): number {
}
Worked examples
| Call | Result |
|---|---|
boardNeighbours([[1,1,1],[1,0,1],[1,1,1]], 1, 1) | 8 |
boardNeighbours([[0,0,0],[0,1,0],[0,0,0]], 1, 1) | 0 |
boardNeighbours([[1,1],[1,1]], 0, 0) | 3 |
boardNeighbours([[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 TypeScript
function boardNeighbours(grid: number[][], row: number, col: number): number {
let count = 0;
const rows = grid.length;
const cols = grid[0].length;
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue;
const r = row + dr, c = col + dc;
if (r >= 0 && r < rows && c >= 0 && c < cols && grid[r][c] === 1) count++;
}
}
return count;
}