Problem Description
Given an m x n board representing the state of Conway's Game of Life where each cell is live (1) or dead (0), update the board to its next state by applying the four rules simultaneously. Changes must be made in-place without using a duplicate board.
Key Insights
- The update must happen simultaneously, so changes in one cell cannot immediately affect its neighbors.
- Use an in-place strategy by encoding the transition states within the board.
- Introduce temporary values to represent state changes: for example, mark a cell that was live but now dead, and a cell that was dead but now live.
- When counting live neighbors, consider the cell's original state, which can be recovered using the absolute value or a defined mapping.
Space and Time Complexity
Time Complexity: O(m * n) – we check each cell and its at most 8 neighbors. Space Complexity: O(1) – updates are performed in-place without extra auxiliary storage.
Solution
We can solve the problem in-place by using intermediate states:
- Use -1 to represent a cell that was originally live (1) but becomes dead (0).
- Use 2 to represent a cell that was originally dead (0) but becomes live (1).
During the first pass, for each cell count the live neighbors (treating a cell as originally live if its value is 1 or -1). Then, update the cell using the Game of Life rules:
- If a cell is dead (0) and has exactly 3 live neighbors, mark it as 2 (becomes live).
- If a cell is live (1) and has fewer than 2 or more than 3 live neighbors, mark it as -1 (dies).
In a second pass, finalize the board by converting cells:
- If the value is > 0 (either 1 or 2), set the cell to 1.
- Otherwise, set the cell to 0.
This method leverages in-place modifications while correctly computing neighbor counts based on original states.