美文网首页Leetcode
Leetcode 289. Game of Life

Leetcode 289. Game of Life

作者: SnailTyan | 来源:发表于2021-09-27 10:48 被阅读0次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Game of Life

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

  1. https://leetcode.com/problems/game-of-life/

相关文章

网友评论

    本文标题:Leetcode 289. Game of Life

    本文链接:https://www.haomeiwen.com/subject/iiggbltx.html