289 Game of Life
class Solution:
def gameOfLife(self, board):
"""
:type board: List[List[int]]
: (0) - dead
: (1) - live
: (2) - dead to live
: (3) - live to dead
:rtype: void Do not return anything, modify board in-place instead.
"""
def in_board(r, c, R, C):
return r >= 0 and c >= 0 and c < C and r < R
neighbors = [(1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for i, row in enumerate(board):
for j, cell in enumerate(row):
count_live = 0
for r, c in neighbors:
if in_board(i + r, j + c, len(board), len(board[0])) and (board[i + r][j + c] == 1 or board[i + r][j + c] == 3):
count_live += 1
# Any live cell with fewer than two live neighbors dies, as if caused by under-population
# Any live cell with more than three live neighbors dies, as if by over-population
if (count_live < 2 or count_live > 3)and (cell == 1 or cell == 3):
board[i][j] = 3 # live to dead
# Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction
elif (count_live == 3) and (cell == 0 or cell == 2):
board[i][j] = 2 # dead to live
for i, row in enumerate(board):
for j, cell in enumerate(row):
if cell == 3:
board[i][j] = 0
elif cell == 2:
board[i][j] = 1Last updated