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
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int boardNeighbours(List<List<Integer>> grid, int row, int col) {
}
Worked examples
| Call | Result |
|---|---|
boardNeighbours(Main.<List<Integer>>ls(Main.<Integer>ls(1, 1, 1), Main.<Integer>ls(1, 0, 1), Main.<Integer>ls(1, 1, 1)), 1, 1) | 8 |
boardNeighbours(Main.<List<Integer>>ls(Main.<Integer>ls(0, 0, 0), Main.<Integer>ls(0, 1, 0), Main.<Integer>ls(0, 0, 0)), 1, 1) | 0 |
boardNeighbours(Main.<List<Integer>>ls(Main.<Integer>ls(1, 1), Main.<Integer>ls(1, 1)), 0, 0) | 3 |
boardNeighbours(Main.<List<Integer>>ls(Main.<Integer>ls(1, 0, 1), Main.<Integer>ls(0, 1, 0), Main.<Integer>ls(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 Java
int boardNeighbours(List<List<Integer>> grid, int row, int col) {
int count = 0;
int rows = grid.size();
int cols = grid.get(0).size();
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
if (dr == 0 && dc == 0) continue;
int r = row + dr, c = col + dc;
if (r >= 0 && r < rows && c >= 0 && c < cols && grid.get(r).get(c) == 1) count++;
}
}
return count;
}