文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Game of Life2. Solution
解析:Version 1,遍历所有细胞,统计其周围八个细胞的存活个数,根据规则判断当前细胞状态是否需要改变,如果需要,将其位置及要更新的状态保存到数组中,遍历数组,更新board
即可。
- Version 1
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])
cells = []
for i in range(m):
for j in range(n):
count = 0
if i > 0:
count += board[i-1][j]
if j > 0:
count += board[i-1][j-1]
if j < n - 1:
count += board[i-1][j+1]
if i < m - 1:
count += board[i+1][j]
if j > 0:
count += board[i+1][j-1]
if j < n - 1:
count += board[i+1][j+1]
if j > 0:
count += board[i][j-1]
if j < n - 1:
count += board[i][j+1]
if board[i][j] == 1 and (count < 2 or count > 3):
cells.append((i, j, 0))
if count == 3 and board[i][j] == 0:
cells.append((i, j, 1))
for x, y, state in cells:
board[x][y] = state
网友评论