SDE & MLE Prep

289. Game of Life

Problem

Advance Conway's Game of Life one generation, in place. Each cell of board is live (1) or dead (0). A live cell with 2 or 3 live neighbours (of 8) survives, a dead cell with exactly 3 becomes live, and every other cell is dead next round. All cells update simultaneously.

Example: [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] → [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]

Constraints: follow-up: update in place, without a copy of the board.

Update in place by storing the next state in bit 1 while bit 0 keeps the current state. Count live neighbours with cell & 1, then shift every cell right by one.

Complexity: O(m·n) time, O(1) space.

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        R, C = len(board), len(board[0])
        for r in range(R):
            for c in range(C):
                live = sum(board[i][j] & 1 for i in range(max(0, r - 1), min(R, r + 2))
                           for j in range(max(0, c - 1), min(C, c + 2))) - (board[r][c] & 1)
                if live == 3 or (live == 2 and board[r][c] & 1):
                    board[r][c] |= 2
        for r in range(R):
            for c in range(C):
                board[r][c] >>= 1