/289. Game of Life

289. Game of Life

Medium
Arrays72.4% acceptance

Given a 2D integer matrix grid of size m x n, where each element is either 0 (dead) or 1 (alive), update grid in-place to its next state according to the following rules: 1) Any live cell with fewer than two live neighbors becomes dead. 2) Any live cell with two or three live neighbors remains alive. 3) Any live cell with more than three live neighbors becomes dead. 4) Any dead cell with exactly three live neighbors becomes alive. Neighbors are the eight adjacent cells (horizontal, vertical, and diagonal). All updates must be applied simultaneously. Do not return anything; modify grid in-place.

Example 1

Input: [[1,0,0],[0,1,0],[0,0,1]]

Output: [[0,0,0],[0,0,1],[0,1,0]

Explanation: Each cell is updated according to the rules.

Example 2

Input: [[1,1,1],[1,0,1],[1,1,1]]

Output: [[1,0,1],[0,0,0],[1,0,1]

Explanation: Central cell dies due to over-population; corners remain alive.

Constraints

  • 1 <= len(grid) <= 25
  • 1 <= len(grid[0]) <= 25
  • grid[i][j] in {0, 1}
Python (current runtime)

Case 1

Input: [[0,0,1],[1,1,0],[0,1,0]]

Expected: [[0,1,0],[1,1,1],[0,1,0]]

Case 2

Input: [[1,0],[0,1]]

Expected: [[0,0],[0,0]]

Case 3

Input: [[1,1,0],[0,1,0],[0,0,1]]

Expected: [[1,1,1],[1,0,1],[0,1,0]]