Problems/289. Game of Life

289. Game of Life

MediumMatrixGraphSimulation

According to Conway's Game of Life rules, cells on a 2D grid live or die based on their 8 neighbors. Given the current state of a board, return a new board representing the next generation's state.

Transitions are governed by these rules:

  1. Any live cell (1) with fewer than two live neighbors dies (underpopulation).
  2. Any live cell (1) with two or three live neighbors lives on to the next generation.
  3. Any live cell (1) with more than three live neighbors dies (overpopulation).
  4. Any dead cell (0) with exactly three live neighbors becomes a live cell (reproduction).
Example 1
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] ]
Applying Conway's Game of Life rules simultaneously to every cell transforms the grid to the next generation state.
Example 2
Input: board = [ [1, 1], [1, 1] ]
Output: [ [1, 1], [1, 1] ]
A block of 2x2 live cells is a stable pattern (Still Life); each cell has exactly 3 neighbors, so it remains unchanged.
Example 3
Input: board = [ [0, 1, 0], [0, 1, 0], [0, 1, 0] ]
Output: [ [0, 0, 0], [1, 1, 1], [0, 0, 0] ]
This is an oscillator pattern known as a Blinker. The vertical line of 3 cells transitions into a horizontal line of 3 cells.
Visualizer

Visualizer will appear here