自学内容网 自学内容网

【LeetCode】289.生命游戏

如何原地对数组进行修改是比较困难的,递归的算法无法做到。那有什么方式能简化吗?可以设计多种数字用于记录细胞的状态,不同的数字记录了不同的时刻和状态,从而简化了题目。

1.题目

在这里插入图片描述

2.思想

本题题意虽然比较复杂,但是还是属于比较简单的一道题。有两种思路可以解:

  • copy一个一模一样的数组,然后挨个计算条件,将结果放到原数组中。
  • 更改状态。
    说实话,第二种思想真的是很有意思。时刻分成两种:现在和未来;状态分成“死”或者“活”。所以就可以得到下面这张图:
    在这里插入图片描述
    根据设计的思路就可以得到下面这个代码。

3.代码

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])
        for i in range(m):
            for j in range(n):
                alive_cnt = self.getNum(i,j,m,n,board)
                # 现在是活的,后面死了
                if alive_cnt < 2 and board[i][j] == 1: # 条件1
                    board[i][j] = 4 
                elif alive_cnt == 2 and board[i][j] == 1: # 条件2-1
                    board[i][j] = 5
                elif alive_cnt == 3 and board[i][j] == 1: # 条件2-2
                    board[i][j] = 5                                
                elif alive_cnt > 3 and board[i][j] == 1:# 条件3
                    board[i][j] = 4
                elif alive_cnt == 3 and board[i][j] == 0:# 条件3
                    board[i][j] = 3
        # print(board)
        for i in range(m):
            for j in range(n):
                board[i][j] %= 2

    # 返回活着的细胞个数
    # m行n列
    def getNum(self,x,y,m,n,board):
        alive_cnt = 0
        a = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
        for i in a:
            new_x, new_y = x+i[0], y+i[1]
            if 0<=new_x<m and 0<=new_y <n:
                # 要看之前的状态
                if board[new_x][new_y] == 1 or board[new_x][new_y] == 4 or board[new_x][new_y] == 5:
                    alive_cnt+=1                
        return alive_cnt

原文地址:https://blog.csdn.net/liu16659/article/details/142441827

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!