- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/game-of-life
- topics: 2D Array
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):
- Any live cell with fewer than two live neighbors dies as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board. In this process, births and deaths occur simultaneously.
Given the current state of the board, update the board to reflect its next state.
Note that you do not need to return anything.
Idea
Use recursion for 1 cells and their neighbors, use memo for visited cells and cells to update
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
visited = set()
N = len(board)
M = len(board[0])
memo = [[None] * M for _ in range(N)]
def nbr_live_neighbors(i, j):
count = 0
for t in range(i-1, i+2):
for k in range(j-1, j+2):
if t == i and j == k:
continue
if (t >= 0 and k >= 0 and t < N and k < M
and board[t][k] == 1):
count += 1
if count > 3:
return count
return count
def update(i, j):
nonlocal memo
if memo[i][j] is not None:
return
memo[i][j] = False
nb_neighbors = nbr_live_neighbors(i, j)
if board[i][j] == 1:
if nb_neighbors < 2 or nb_neighbors > 3:
memo[i][j] = True
for t in range(i-1, i+2):
for k in range(j-1, j+2):
if t == i and j == k:
continue
if t >= 0 and k >= 0 and t < N and k < M:
update(t, k)
elif nb_neighbors == 3:
memo[i][j] = True
for i in range(N):
for j in range(M):
if board[i][j] == 1:
update(i, j)
for i in range(N):
for j in range(M):
if memo[i][j]:
board[i][j] = 1 - board[i][j]