<
>

LeetCode 289. 生命游戏

2020-06-28 14:24:35 来源:易采站长站 作者:易采站长站整理

for row in range(rows):
for col in range(cols):
# 用以标记存活的细胞数量
live = 0
# 查看相邻位置
for dx, dy in directions:
r = row + dx
c = col + dy

if (r >= 0 and r = 0 and c < cols) and (board[r][c] == 1 or board[r][c] == 'dying'):
# 这里 'dying' 用作标记,表示由活的变成死的
live += 1

# 现在判断细胞是否能存活
# 定律 1,3 ,细胞不能存活
if board[row][col] == 1 and (live 3):
board[row][col] = 'dying'
# 定律 4,细胞能够复活
if board[row][col] == 0 and live == 3:
board[row][col] = 'relive'

# 重新遍历,根据标记修改细胞存活状态
for row in range(rows):
for col in range(cols):
if board[row][col] == 'relive':
board[row][col] = 1
if board[row][col] == 'dying':
board[row][col] = 0


实现效果

实现结果

以上就是使用额外的状态标记模拟,解决《生命游戏》问题的主要内容。

欢迎关注微信公众号《书所集录》

作者:"大梦三千秋

暂时禁止评论

微信扫一扫

易采站长站微信账号