



The main difficulty is that all cells must be updated simultaneously, while we are required to modify the board in-place.
To solve this, we encode both the original state and the next state in a single cell using temporary values.
State Encoding
| Value | Meaning |
|---|---|
0 | dead → dead |
1 | live → live |
2 | dead → live (birth) |
3 | live → dead (death) |
Key observation:
dirs = [(-1,-1), (-1,0), (-1,1),
( 0,-1), ( 0,1),
( 1,-1), ( 1,0), ( 1,1)](i, j):class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
m, n = len(board), len(board[0])
# 8 directions
dirs = [(-1, -1), (-1, 0), (-1, 1),
( 0, -1), ( 0, 1),
( 1, -1), ( 1, 0), ( 1, 1)]
def was_live(x: int) -> bool:
# originally live cells are 1 (live->live) or 3 (live->dead)
return x == 1 or x == 3
# 1) State encoding
# (0: 0->0, 1: 1->1, 2: 0->1, 3: 1->0)
for i in range(m):
for j in range(n):
live_neighbors = 0
for di, dj in dirs:
ni, nj = i + di, j + dj
if 0 <= ni < m and 0 <= nj < n and was_live(board[ni][nj]):
live_neighbors += 1
if was_live(board[i][j]): # originally live
if live_neighbors < 2 or live_neighbors > 3:
board[i][j] = 3 # live -> dead
else:
board[i][j] = 1 # live -> live
else: # originally dead
if live_neighbors == 3:
board[i][j] = 2 # dead -> live
else:
board[i][j] = 0 # dead -> dead
# 2) State encoding -> Finalize to 0/1
for i in range(m):
for j in range(n):
board[i][j] = 1 if board[i][j] in (1, 2) else 0