Ctrl K

Next Step of a Cell Colony

Medium
The m × n grid field is a colony of cells: 1 is a live cell, 0 is an empty one. A cell's neighbours are the up to eight cells around it (sides and diagonals); there are no cells beyond the edge. In one step all cells change at the same time: - a live cell with 2 or 3 live neighbours stays alive, otherwise it dies; - an empty cell with exactly 3 live neighbours comes alive, otherwise it stays empty. Advance the colony by one step and return the new grid. Note that a cell's new state depends only on the old states of its neighbours. Try to do it without copying the grid.
Example 1
field=[[0, 0, 0], [1, 1, 1], [0, 0, 0]] → [[0, 1, 0], [0, 1, 0], [0, 1, 0]]

The horizontal row of three turns vertical: [[0, 1, 0], [0, 1, 0], [0, 1, 0]]. The end cells have one live neighbour each and die; the top and bottom middle cells have exactly three and come alive.

Example 2
field=[[1, 1], [1, 1]] → [[1, 1], [1, 1]]

Every cell of the square has three live neighbours, so the field does not change.

Example 3
field=[[1, 0, 1]] → [[0, 0, 0]]

Neither live cell has a live neighbour, so both die: [[0, 0, 0]].

Constraints
  • 1 ≤ m, n ≤ 25
  • field[i][j] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSpiral Readout MediumSpiral-Numbered Square MediumZigzag Diagonal Sweep MediumMatch-Three Cascade MediumOutward Spiral Walk Medium
loading Python…
Input
field=[[0, 0, 0], [1, 1, 1], [0, 0, 0]]
Expected
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

Run checks the first 3 tests in your browser. Submit checks all 35 tests on the server, hidden ones included.