
思路
深度优先遍历的思路,对当前细胞八个方向进行遍历,统计存活的细胞,并通过标记修改board数组,如果细胞死亡则标记为-1,细胞复活标记为2。再次遍历数组,然后根据标记修改数组即可
python
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m=len(board)
n=len(board[0])
directions=[(-1,0),(0,-1),(0,1),(1,0),(1,1),(-1,1),(-1,-1),(1,-1)]
def dfs(i,j):
count=0
for x,y in directions:
new_x=x+i
new_y=y+j
if 0<=new_x<m and 0<=new_y<n and abs(board[new_x][new_y])==1:
count+=1
return count
for i in range(m):
for j in range(n):
live=dfs(i,j)
if board[i][j]==1 and live<2:
board[i][j]=-1
elif board[i][j]==1 and live>3:
board[i][j]=-1
elif board[i][j]==0 and live==3:
board[i][j]=2
for i in range(m):
for j in range(n):
if board[i][j]<0:
board[i][j]=0
elif board[i][j]>0:
board[i][j]=1
值得注意的是,abs(board[new_x][new_y])==1,是为了正确统计当前细胞的邻居原本是"活"的数量。因为在原地修改的时候-1表示原来是活的,下一个状态要变成死