Game of Life
Given a board of 0s (dead) and 1s (live), return the next state according to Conway's Game of Life rules.
Rules applied simultaneously to every cell based on the current state:
- Live cell with fewer than 2 live neighbors dies (underpopulation).
- Live cell with 2 or 3 live neighbors lives.
- Live cell with more than 3 live neighbors dies (overpopulation).
- Dead cell with exactly 3 live neighbors becomes live (reproduction).
Neighbors are the 8 adjacent cells (horizontal, vertical, diagonal). The functional API returns the next-state board; callers should use the returned value as the result.
Examples
Input: [[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]]
Input: [[1,1],[1,0]]
Output: [[1,1],[1,1]]
Hints
Use a temporary board to store the next state while calculating live neighbors to avoid overwriting the current state prematurely.
Implement boundary checks to handle edge cells (corners and borders) where neighbor counts may differ due to fewer adjacent cells.
Optimize neighbor counting by iterating through all 8 possible directions (including diagonals) for each cell while ensuring no out-of-bounds access.
Related Problems
Game of Life
Given a board of `0`s (dead) and `1`s (live), return the next state according to Conway's Game of Life rules.