Drill

ProblemsTypeScript › games

Count neighbouring live cells

mediumgamesTypeScript

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

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

Solve it in the editor →

Where you start

function boardNeighbours(grid: number[][], row: number, col: number): number {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More games problems in TypeScript