Drill

ProblemsGo › games

Count neighbouring live cells

mediumgamesGridsArraysGo

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

Go 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

func boardNeighbours(grid [][]int, row int, col int) int {
	
}

Worked examples

CallResult
boardNeighbours([][]int{[]int{1, 1, 1}, []int{1, 0, 1}, []int{1, 1, 1}}, 1, 1)8
boardNeighbours([][]int{[]int{0, 0, 0}, []int{0, 1, 0}, []int{0, 0, 0}}, 1, 1)0
boardNeighbours([][]int{[]int{1, 1}, []int{1, 1}}, 0, 0)3
boardNeighbours([][]int{[]int{1, 0, 1}, []int{0, 1, 0}, []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 Go
func boardNeighbours(grid [][]int, row int, col int) int {
	count := 0
	rows := len(grid)
	cols := len(grid[0])
	for dr := -1; dr <= 1; dr++ {
		for dc := -1; dc <= 1; dc++ {
			if dr == 0 && dc == 0 {
				continue
			}
			r, c := row+dr, 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 Go