According to Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”
The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
rows, cols = len(board), len(board[0])
maps = [[0 for i in range(cols)] for j in range(rows)]
dxy = [[1, 0], [1, 1], [1, -1], [0, 1], [0, -1], [-1, 0], [-1, 1], [-1, -1]]
for r in range(rows):
for c in range(cols):
cnts = 0
for k in range(8):
neighbor_r = r + dxy[k][0]
neighbor_c = c + dxy[k][1]
if neighbor_r >= 0 and neighbor_r < rows and neighbor_c >= 0 and neighbor_c < cols:
cnts += board[neighbor_r][neighbor_c]
if board[r][c] and cnts >= 2 and cnts <= 3 or not board[r][c] and cnts == 3:
maps[r][c] = 1
else:
maps[r][c] = 0
for r in range(rows):
for c in range(cols):
board[r][c] = maps[r][c]