码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】289. Game of Life

时间:2018-09-17 19:36:09      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:info   http   col   style   boa   etl   pen   etc   dead   

题目如下:

技术分享图片

解题思路:因为本题要求的是直接在输入的数组上面修改,而且细胞的生死转换是一瞬间的事情,所以需要引入两个中间状态,待死和待活。这两个中间状态用于在四条规则判断的时候是“活”和“死”,但是呈现在最终的结果是“死”和“活”。

代码如下:

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

标签:info   http   col   style   boa   etl   pen   etc   dead   

原文地址:https://www.cnblogs.com/seyjs/p/9660754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!