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
C++ 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(std::vector<std::vector<int>> grid, int row, int col) {
}
Worked examples
| Call | Result |
|---|---|
boardNeighbours(std::vector<std::vector<int>>{std::vector<int>{1, 1, 1}, std::vector<int>{1, 0, 1}, std::vector<int>{1, 1, 1}}, 1, 1) | 8 |
boardNeighbours(std::vector<std::vector<int>>{std::vector<int>{0, 0, 0}, std::vector<int>{0, 1, 0}, std::vector<int>{0, 0, 0}}, 1, 1) | 0 |
boardNeighbours(std::vector<std::vector<int>>{std::vector<int>{1, 1}, std::vector<int>{1, 1}}, 0, 0) | 3 |
boardNeighbours(std::vector<std::vector<int>>{std::vector<int>{1, 0, 1}, std::vector<int>{0, 1, 0}, std::vector<int>{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 C++
int boardNeighbours(std::vector<std::vector<int>> grid, int row, int col) {
int count = 0;
int rows = (int) grid.size();
int cols = (int) grid[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[r][c] == 1) count++;
}
}
return count;
}