Leetcode 289. Game of Life
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 289. Game of Life相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. 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
Reference
以上是关于Leetcode 289. Game of Life的主要内容,如果未能解决你的问题,请参考以下文章