Game of Life

Conway's Game of Life runs on an `m x n` board where every cell is live (`1`) or dead (`0`). Each cell looks at its eight neighbours (horizontal, vertical and diagonal): 1. A live cell with fewer than two live neighbours dies. 2. A live cell with two or three live neighbours lives on. 3. A live cell with more than three live neighbours dies. 4. A dead cell with exactly three live neighbours becomes live. All cells update at the same moment. Update `board` in place to its next state; do not return anything.

30:00

Game of Life
medium
Free written solution
Topics
Companies

Conway's Game of Life runs on an m x n board where every cell is live (1) or dead (0). Each cell looks at its eight neighbours (horizontal, vertical and diagonal):

  1. A live cell with fewer than two live neighbours dies.
  2. A live cell with two or three live neighbours lives on.
  3. A live cell with more than three live neighbours dies.
  4. A dead cell with exactly three live neighbours becomes live.

All cells update at the same moment. Update board in place to its next state; do not return anything.

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]]
Constraints:
  • m==board.lengthm == \text{board.length}

  • n==board[i].lengthn == \text{board}[i].\text{length}

  • 1≤m,n≤251 \leq m, n \leq 25

  • board[i][j]\text{board}[i][j] is 00 or 11

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"board":[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]}

Pass 1 judges every cell but only writes into bit 1, so bit 0 keeps the old generation for the neighbours still to come.

pass 1: fill = alive now (bit 0), green dot = alive next (bit 1)

0
1
0
0
0
1
1
1
1
0
0
0

live neighbours

-

live, < 2 neighbours: dies

live, 2 or 3: survives

live, > 3: dies

dead, exactly 3: born

dead, otherwise: stays dead

two states in one int (bit 1 = next, bit 0 = now)

0

00: dead, stays dead

1

01: live, will die

2

10: dead, will live

3

11: live, stays live

Variables
VariableValue
m4
n3
DepthFunction Call
Stack empty
0/29