leetcode289. Game of Life
Posted seyjs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode289. Game of Life相关的知识,希望对你有一定的参考价值。
题目如下:
解题思路:因为本题要求的是直接在输入的数组上面修改,而且细胞的生死转换是一瞬间的事情,所以需要引入两个中间状态,待死和待活。这两个中间状态用于在四条规则判断的时候是“活”和“死”,但是呈现在最终的结果是“死”和“活”。
代码如下:
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]
以上是关于leetcode289. Game of Life的主要内容,如果未能解决你的问题,请参考以下文章