Game of Life

Medium

Topics
ArrayMatrixSimulation

The board is an m x n grid of cells, each 1 (live) or 0 (dead). Every cell has up to eight neighbours — horizontal, vertical and diagonal.

Return the board after one step, where every cell updates simultaneously according to its live neighbour count:

  • a live cell with fewer than 2 live neighbours dies;
  • a live cell with 2 or 3 live neighbours lives on;
  • a live cell with more than 3 live neighbours dies;
  • a dead cell with exactly 3 live neighbours becomes live.

On this judge the rows of the returned board are shown separated by |.

Example 1

before0010100121113000012
after0000110120113010012
borndiedsurvived
Each cell counts its eight neighbours, diagonals included, and every cell updates from the same starting board — the shading marks what each cell is about to do, judged on the board above and not on any partly-updated one. Here 2 cells are born and 2 cells die in this step.
2D grid — one row per line.
Input:  grid = [[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]]
Explanation: The cell at (3,1) has exactly three live neighbours above it and is born, while (0,1) has only one and dies.

Example 2

before01111001
after01111101
bornsurvived
Input:  grid = [[1,1],[1,0]]
Output: [[1,1],[1,1]]
Explanation: Each live cell has two live neighbours and survives, and the dead corner has three and is born.

Example 3

before00010001
after00010001
Input:  grid = [[0,0],[0,0]]
Output: [[0,0],[0,0]]
Explanation: An empty board stays empty — nothing has three neighbours.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 25
  • grid[i][j] is 0 or 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

The word doing all the work is simultaneously. Every cell’s new value depends on the board as it was before the step, so writing a new value into a cell before its neighbours have been read corrupts their counts.

The straightforward fix is a second board: read from the old one, write to the new one, and nothing can interfere. That is the right first answer and it is what the code below does.

The in-place version is the reason this problem gets asked, and it is worth knowing the idea: a cell only needs to carry two bits, its old state and its new one. Encoding the new state in a higher bit lets one pass compute every cell while the low bit still holds the original board, and a second pass shifts the new state down. The neighbour count then reads the low bit and is unaffected by cells already decided.

Approach

  1. Allocate an output board of the same size.
  2. For each cell, count live neighbours by looking at the eight offsets around it in the input board, skipping anything off the edge.
  3. Apply the rules: a live cell survives on a count of 2 or 3; a dead cell is born on a count of exactly 3; everything else is dead.
  4. Write the result into the output board and return it.

Walkthrough

grid = [[0,1,0],
        [0,0,1],
        [1,1,1],
        [0,0,0]]

cell    state  live neighbours        becomes
(0,1)   live    1  -- (1,2)? no, only (0,0)/(1,0)/(1,1)/(1,2)
                   of which (1,2) is live     dies   0
(1,0)   dead    3  -- (0,1) (2,0) (2,1)       born   1
(1,2)   live    2  -- (2,1) (2,2)             lives  1
(2,1)   live    3  -- (2,0) (2,2) (1,2)       lives
        but also (1,1) dead, (3,*) dead -> count 3  1
(3,1)   dead    3  -- (2,0) (2,1) (2,2)       born   1

Every count above is taken from the ORIGINAL board. Reading
(1,0) as live while counting (0,1) would be the bug this
problem exists to catch.

Complexity

  • Time — O(m * n): eight neighbour reads per cell, a fixed cost.
  • Space — O(m * n): the output board. The bit-encoding variant is O(1) beyond the input.

Common Pitfalls

  • Updating the board in place without encoding. A cell that has already flipped feeds the wrong value into its neighbours’ counts, and the error spreads across the sweep.
  • Counting only the four orthogonal neighbours. There are eight — the diagonals matter, and example 2 depends on one.
  • Counting the cell itself. The offsets must exclude (0, 0).
  • Running the rules more than once. The question asks for exactly one step.

Full Solution — all languages

class Solution:
    def gameOfLife(self, grid):
        NEIGHBOURS = ((-1, -1), (-1, 0), (-1, 1), (0, -1),
                      (0, 1), (1, -1), (1, 0), (1, 1))
        rows, cols = len(grid), len(grid[0])
        out = [[0] * cols for _ in range(rows)]
        for r in range(rows):
            for c in range(cols):
                live = 0
                for dr, dc in NEIGHBOURS:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                        live += 1
                if grid[r][c] == 1:
                    out[r][c] = 1 if live in (2, 3) else 0
                else:
                    out[r][c] = 1 if live == 3 else 0
        return out
SensAI
Beta
Tap the mic to stop voice mode