边工作边刷题:70天一遍leetcode: day 56-2

Game of Life

要点:这题首先要记住题,

  • 具体来说题的核心是什么:即2d处理的两步顺序的矛盾:如果前一步处理了并记录了,那么后面的处理需要的信息就被wipe了。这题处理的方法就是记录的信息要包含修改之前和之后的信息,一共有4种可能情况:live => live, live => dead, dead => live, dead => dead。
  • 可以用1,2,3,4来encode这4种情况,encode的依据是什么?
    • 首先最终目标是2个状态,为了方便从4=>2,2个相同状态要分开(取%)。
    • 改变board状态只有2种情况:从live=>dead,或者dead=>live。又因为board原本用0表示dead,1表示live,所以用2,3来表示两种变化
  • 综合上面2点,找到encode的规律

错误点:

  • board 0表示dead 1表示live
  • 注意当前点只可能是0或者1,但是算neighbor的时候要考虑2和3
class Solution(object):
    def gameOfLife(self, board):
        """
        :type board: List[List[int]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        m = len(board)
        n = len(board[0])
        dir = [(0,1),(1,0),(1,1),(-1,0),(0,-1),(-1,-1),(-1,1),(1,-1)]
        for i in xrange(m):
            for j in xrange(n):
                live = 0
                for k in xrange(8):
                    i0,j0 = i+dir[k][0],j+dir[k][1]
                    if i0>=0 and i0<m and j0>=0 and j0<n and (board[i0][j0]==1 or board[i0][j0]==2):
                        live+=1
                    
                if live==3 and board[i][j]==0:
                    board[i][j]=3
                
                if (live>3 or live<2) and board[i][j]==1:
                    board[i][j]=2
        
        for i in xrange(m):
            for j in xrange(n):
                board[i][j]%=2
                
                        

原文地址:https://www.cnblogs.com/absolute/p/5690323.html