1. 程式人生 > >【leetcode】289. Game of Life

【leetcode】289. Game of Life

count sel 結果 for span append ins 直接 instead

題目如下:

技術分享圖片

解題思路:因為本題要求的是直接在輸入的數組上面修改,而且細胞的生死轉換是一瞬間的事情,所以需要引入兩個中間狀態,待死和待活。這兩個中間狀態用於在四條規則判斷的時候是“活”和“死”,但是呈現在最終的結果是“死”和“活”。

代碼如下:

class Solution(object):
    def getLiveCount(self,board,x,y):
        l = [(0,-1),(0,1),(-1,0),(1,0),(-1,-1),(1,1),(-1,1),(1,-1)]
        count = 0
        for i in l:
            if
board[x+i[0]][y+i[1]] == 1 or board[x+i[0]][y+i[1]] == 4: count += 1 return count def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ # 2 means boundary
# 3 means from dead to live # 4 means from live to dead for i in board: i.append(2) i.insert(0,2) l = [2] * len(board[0]) board.append(l[::]) board.insert(0,l[::]) for i in range(1,len(board)-1): for j in range(1,len(board[i])-1):
count = self.getLiveCount(board,i,j) if board[i][j] == 0 and count == 3: board[i][j] = 3 elif board[i][j] == 1 and (count < 2 or count > 3): board[i][j] = 4 for i in range(1,len(board)-1): for j in range(1,len(board[i])-1): if board[i][j] == 3: board[i][j] = 1 elif board[i][j] == 4: board[i][j] = 0 del board[0] del board[-1] for i in board: del i[0] del i[-1]

【leetcode】289. Game of Life