1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 class Solution:
def gameOfLife(self, board: List[List[int]]) > None:
m, n = len(board), len(board[0])
directions = [(1,0), (1,0), (0,1), (0,1), (1,1), (1,1), (1,1), (1,1)]
for i in range(m):
for j in range(n):
live_neighbors = 0
for d in directions:
ni, nj = i + d[0], j + d[1]
if 0 <= ni < m and 0 <= nj < n and (board[ni][nj] == 1 or board[ni][nj] == 1):
live_neighbors += 1
if board[i][j] == 1 and (live_neighbors < 2 or live_neighbors > 3):
board[i][j] = 1 # Transition from live to dead
elif board[i][j] == 0 and live_neighbors == 3:
board[i][j] = 2 # Transition from dead to live
# Change temporary states back to final states
for i in range(m):
for j in range(n):
if board[i][j] == 1:
board[i][j] = 0
elif board[i][j] == 2:
board[i][j] = 1
