Game of Life
The key idea
Problem
The board is an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, and diagonal) using the following four rules (taken simultaneously):
1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board. In this process, births and deaths occur simultaneously. Given the current state of the board, update the board to reflect its next state.
Note that you do not need to return anything. Make the changes in place. Could you solve it in place using the original board and only constant extra memory?
Constraints
m == board.lengthn == board[i].length1 <= m, n <= 25board[i][j]is0or1.
Examples
Complexity
Time: O(m * n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Matrix / Grid problems
- Island PerimeterEASY
- Rotate ImageMEDIUM
- Search a 2D Matrix IIMEDIUM
- Set Matrix ZeroesMEDIUM
- Spiral MatrixMEDIUM
- Spiral Matrix IIMEDIUM
- Transpose MatrixEASY