Python easy-to-understand AC solution w/ comments


  • 0
    W
    class Solution(object):
        def gameOfLife(self, board):
            """
            :type board: List[List[int]]
            :rtype: void Do not return anything, modify board in-place instead.
            """
            # use two bits to represent now and before
            # first bit from the tail represents before
            # second bit from the tail represents now
            # too judge if it previous lived, do cell&1 and 
            # follow the rules
            if not board: return
            directions = [[1,1],[1,0],[0,1],[-1,0],[0,-1],[-1,-1],[-1,1],[1,-1]]
            for i in xrange(len(board)):
                for j in xrange(len(board[-1])):
                    live = 0
                    for u,v in directions:
                        x,y = i+u,j+v
                        # if living valid neighbor cell
                        if 0<=x<len(board) and 0<=y<len(board[-1]) and (board[x][y]&1): live += 1
                    if not (board[i][j]&1):
                        # previously dead cell
                        if live==3: board[i][j] = int('10',2)
                    else:
                        # previously lived cell
                        if live<2 or live>3: 
                            board[i][j] = int('01',2)
                        else:
                            board[i][j] = int('11',2)
            for i in xrange(len(board)):
                for j in xrange(len(board[-1])):
                    board[i][j]>>=1
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.