Python short Code


  • 0

    Using the same idea of this post, just a Python version.

    class Solution(object):
        def gameOfLife(self, board):
            if not board:
                return board
            h, w = len(board), len(board[0])
            def count(y, x):
                cnt = 0
                dirs = [[0, 1], [0, -1], [1, 0], [-1, 0], [1, 1], [1, -1], [-1, -1], [-1, 1]]
                for i in range(len(dirs)):
                    ty, tx = y + dirs[i][0], x + dirs[i][1]
                    if 0 <= ty < h and 0 <= tx < w and board[ty][tx] & 1:
                        cnt += 1
                return cnt
            for i in range(h):
                for j in range(w):
                    cnt = count(i, j)
                    if ( (board[i][j] & 1) == 0 and cnt == 3) or ( (board[i][j] & 1) == 1 and 2 <= cnt <= 3 ):
                        board[i][j] = (1 << 1) + board[i][j]
            for i in range(h):
                for j in range(w):
                    board[i][j] >>= 1              
    

Log in to reply
 

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