Drill

ProblemsC# › games

Count neighbouring live cells

mediumgamesGridsArraysC#

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

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.

Solve it in Python →

Where you start

public int BoardNeighbours(List<List<int>> grid, int row, int col) {
    
}

Worked examples

CallResult
BoardNeighbours(new List<List<int>> { new List<int> { 1, 1, 1 }, new List<int> { 1, 0, 1 }, new List<int> { 1, 1, 1 } }, 1, 1)8
BoardNeighbours(new List<List<int>> { new List<int> { 0, 0, 0 }, new List<int> { 0, 1, 0 }, new List<int> { 0, 0, 0 } }, 1, 1)0
BoardNeighbours(new List<List<int>> { new List<int> { 1, 1 }, new List<int> { 1, 1 } }, 0, 0)3
BoardNeighbours(new List<List<int>> { new List<int> { 1, 0, 1 }, new List<int> { 0, 1, 0 }, new List<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#
public int BoardNeighbours(List<List<int>> grid, int row, int col) {
    int count = 0;
    int rows = grid.Count;
    int cols = grid[0].Count;
    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;
}

The same problem in another language

More games problems in C#