FunctionRacerProblemsRace

Neighbour Counts

EasyGridsPython, JavaScript, TypeScript, Java, C++

Every cell of grid is 0 or 1. Two cells are neighbours when they touch along a side or at a corner, so a cell has up to 8 neighbours and cells on the edge have fewer. Return a new grid of the same shape in which every cell holds the number of its neighbours that are 1 in grid. A cell's own value never counts.

Example 1

grid [[1,0,0],[0,1,0],[0,0,0]]
returns [[1,2,1],[2,1,1],[1,1,1]]

The top-left cell touches 0, 0 and 1, so it gets 1; the centre cell touches all eight others and only one of them is 1.

Example 2

grid [[1,1],[1,1]]
returns [[3,3],[3,3]]

Every cell touches the other three cells, all of which are 1.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Grids problems