단순 구현문제다.
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
def check_live_neighbors(y: int, x: int) -> int:
return sum(board[dy+y][dx+x] for dx, dy in D if 0 <= dx + x < N and 0 <= dy + y < M)
def judge_state(n: int, is_alive: bool) -> int:
if (is_alive and 2 <= n <= 3) or (not is_alive and n == 3):
return 1
return 0
D = ((-1, -1), (-1, 0), (-1, 1), (1, 0), (1, 1), (1, -1), (0, -1), (0, 1))
M, N = len(board), len(board[0])
new_board = [[0 for _ in range(N)] for _ in range(M)]
for i in range(M):
for j in range(N):
live_neighbors = check_live_neighbors(i, j)
new_board[i][j] = judge_state(live_neighbors, board[i][j])
for i in range(M):
for j in range(N):
board[i][j] = new_board[i][j]
O(MN)
O(MN)