289. Game of Life
Asked at 13Amazon27Microsoft25Google23Meta20Bloomberg18Dropbox92Two Sigma90Snap80Riot Games68Adobe55Anduril49Applied Intuition48Salesforce28
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
b = [[0, 1, 0], [0, 0, 1], [1, 1, 1], [0, 0, 0]]
Solution().gameOfLife(b)
assert b == [[0, 0, 0], [1, 0, 1], [0, 1, 1], [0, 1, 0]]
b = [[1, 1], [1, 0]]; Solution().gameOfLife(b)
assert b == [[1, 1], [1, 1]]
class Solution {
public void gameOfLife(int[][] board) {
int R = board.length, C = board[0].length;
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) {
int live = -(board[r][c] & 1);
for (int i = Math.max(0, r - 1); i <= Math.min(R - 1, r + 1); i++)
for (int j = Math.max(0, c - 1); j <= Math.min(C - 1, c + 1); j++) live += board[i][j] & 1;
if (live == 3 || (live == 2 && (board[r][c] & 1) == 1)) board[r][c] |= 2;
}
for (int[] row : board)
for (int c = 0; c < C; c++) row[c] >>= 1;
}
}
func gameOfLife(board [][]int) {
R, C := len(board), len(board[0])
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
live := 0
for i := max(0, r-1); i < min(R, r+2); i++ {
for j := max(0, c-1); j < min(C, c+2); j++ {
live += board[i][j] & 1 // bit 0 = current state
}
}
live -= board[r][c] & 1
if live == 3 || (live == 2 && board[r][c]&1 == 1) {
board[r][c] |= 2 // bit 1 = next state
}
}
}
for r := range board {
for c := range board[r] {
board[r][c] >>= 1
}
}
}