Leetcode 289. Game of Life

文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡(jiǎn)書(shū)

1. Description

Game of Life

2. Solution

解析:Version 1,遍歷所有細(xì)胞,統(tǒng)計(jì)其周?chē)藗€(gè)細(xì)胞的存活個(gè)數(shù),根據(jù)規(guī)則判斷當(dāng)前細(xì)胞狀態(tài)是否需要改變,如果需要,將其位置及要更新的狀態(tài)保存到數(shù)組中,遍歷數(shù)組,更新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/
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容