sagelearnai

Game of Life

Difficulty: Medium · Pattern: Matrix · LeetCode #289

Apply one step of Conway's Game of Life to board (1 = live, 0 = dead), in place. All cells update simultaneously, based on their 8 neighbors:

  1. A live cell with fewer than 2 live neighbors dies (underpopulation).
  2. A live cell with 2 or 3 live neighbors survives.
  3. A live cell with more than 3 live neighbors dies (overpopulation).
  4. A dead cell with exactly 3 live neighbors becomes live (reproduction).

Example

text
[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]  →  [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]

Hints

  1. Updating cells one by one corrupts the neighbor counts of cells that haven't been processed yet.
  2. Values are only 0/1, so there are spare bits. Store the next state in bit 1 and keep the current state in bit 0.

Approach

Pass 1: for each cell, count the live neighbors using board[nr][nc] & 1 (the current state). If the cell should be alive next step (count == 3, or count == 2 and it's alive now), set bit 1: board[r][c] |= 2.

Pass 2: board[r][c] >>= 1.

That's O(mn) time and O(1) space. Follow-up for an infinite board: store only the live cells in a hash set and count neighbors with a hash map. That's how real Life engines (e.g. Hashlife) avoid scanning empty space.

Complexity

Time: O(m·n). Space: O(1).

Python solution
def gameOfLife(board):
    R, C = len(board), len(board[0])
    for r in range(R):
        for c in range(C):
            live = 0
            for dr in (-1, 0, 1):
                for dc in (-1, 0, 1):
                    if (dr or dc) and 0 <= r + dr < R and 0 <= c + dc < C:
                        live += board[r + dr][c + dc] & 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
JavaScript solution
function gameOfLife(board) {
  const R = board.length, C = board[0].length;
  for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) {
    let live = 0;
    for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
      if (!dr && !dc) continue;
      const nr = r + dr, nc = c + dc;
      if (nr >= 0 && nc >= 0 && nr < R && nc < C) live += board[nr][nc] & 1;
    }
    if (live === 3 || (live === 2 && board[r][c] & 1)) board[r][c] |= 2;
  }
  for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) board[r][c] >>= 1;
}