Skip to content
BytePatterns

Next Generation of Cells

MediumMatrix & Grid#eight-neighbours#in-place-encoding~25m

Problem

A simulation keeps a grid of cells, each 1 for alive or 0 for dead. Every cell looks at its eight neighbours (sideways and diagonal) and all cells change at the same moment: a live cell with two or three live neighbours stays alive, a dead cell with exactly three live neighbours comes alive, and every other cell is dead in the next step. Update the grid in place to the next step and return it. The grid has between 1 and 25 rows and columns, and the update should use O(1) extra memory beyond the grid itself.

Examples

Input:  board = [[0, 1, 0], [0, 0, 1], [1, 1, 1], [0, 0, 0]]
Output: [[0, 0, 0], [1, 0, 1], [0, 1, 1], [0, 1, 0]]
Input:  board = [[1, 1], [1, 0]]
Output: [[1, 1], [1, 1]]
Why:    the dead corner has exactly three live neighbours, and each live cell has two
Input:  board = [[1]]
Output: [[0]]
Why:    edge case, a lone live cell has no neighbours and dies

Hints

0 / 3

Stuck on the idea rather than the code? Grid Traversal covers it.