Game of Life
MediumTop Interview 150 Math & GeometryDropboxTwo SigmaSnapProblem
A board is a grid of cells. A cell is alive (1) or dead (0). Each cell has up to eight
neighbors: the cells touching it sideways, up, down and diagonally.
All cells update at the same moment into the next generation:
- A live cell with fewer than two live neighbors dies.
- A live cell with two or three live neighbors stays alive.
- A live cell with more than three live neighbors dies.
- A dead cell with exactly three live neighbors comes alive.
Write the next generation into the board in place. Nothing is returned.
Constraints
- 1 ≤ rows, cols ≤ 25
- board[r][c] is 0 or 1
Examples: pick one to animate
Solutions
Time: Each cell looks at its eight neighbors once, then one more pass shifts every value.
Space: The next state is stored in an unused bit of each cell, so no extra grid is needed.
Each cell only uses one bit (0 or 1), so bit 1 is free to hold the next state. When a cell is updated,
its neighbors still read the old state from bit 0 only (value & 1). A final pass shifts every
value right by one bit, which turns each "next" bit into the new current state.