class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m, n = len(board), len(board[0])
# 方向向量:上、下、左、右、四个对角线
directions = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
# 创建副本用于记录原始状态
copy_board = [[board[i][j] for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
live_neighbors = 0
# 统计周围8个邻居中的活细胞数量
for dx, dy in directions:
ni, nj = i + dx, j + dy
if 0 <= ni < m and 0 <= nj < n and copy_board[ni][nj] == 1:
live_neighbors += 1
# 应用生命游戏规则
if copy_board[i][j] == 1 and (live_neighbors < 2 or live_neighbors > 3):
board[i][j] = 0 # 规则1 & 3
elif copy_board[i][j] == 0 and live_neighbors == 3:
board[i][j] = 1 # 规则4
# 规则2 不需要改变,保持原样