#289

Game of Life

pupil · 535 · lc medium +28 · verified · 72.4% accepted · 6,804 likes · top 82%

play →

Description

Conway's Game of Life is a cellular automaton on an m x n grid where each cell is either alive (1) or dead (0). Each cell interacts with its eight neighbors. All cells update simultaneously according to these four rules:

- A live cell with fewer than two live neighbors dies (underpopulation).

- A live cell with two or three live neighbors survives to the next generation.

- A live cell with more than three live neighbors dies (overpopulation).

- A dead cell with exactly three live neighbors becomes alive (reproduction).

Given the current state of the m x n grid board, update it in-place to the next state. No return value is needed.

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]]

Example 2:

Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]

Code

1
2
3
4
5
6