其他分享
首页 > 其他分享> > Leetcode_1_Array_289生命游戏

Leetcode_1_Array_289生命游戏

作者:互联网

这题是自己写出来的,思路比较简单,就是比较耗内存。思想就是为了简化边界上的数字,而给它四周填满0.

执行用时 :12 ms, 在所有 Python 提交中击败了100.00%的用户

内存消耗 :11.7 MB, 在所有 Python 提交中击败了32.43%的用户

Time Complexity:O(2n)

Space Complexity:O(2n)

Code:

class Solution(object):
    def gameOfLife(self, board):
        """
        :type board: List[List[int]]
        :rtype: None Do not return anything, modify board in-place instead.
        """
        m=len(board)
        n=len(board[0])
        image =[[0 for col in range(n+2)] for row in range(m+2)]
        for i in range(m):
            for j in range(n):
                image[i+1][j+1]=board[i][j]
        for i in range(m):
            for j in range(n):
                # sum=image[i-1][j-1]+image[i-1][j]+image[i-1][j+1]+image[i][j-1]+image[i][j+1]+image[i+1][j-1]+image[i+1][j]+image[i+1][j+1]
                sum=image[i][j]+image[i][j+1]+image[i][j+2]+image[i+1][j]+image[i+1][j+2]+image[i+2][j]+image[i+2][j+1]+image[i+2][j+2]
                if board[i][j]==0:
                    if sum==3:board[i][j]=1
                elif board[i][j]==1:
                    if not(sum==3 or sum==2):board[i][j]=0
                        
        return board

标签:return,Python,image,289,range,board,sum,Array,Leetcode
来源: https://blog.csdn.net/m0_37976836/article/details/98940775