Someone help me to make my code shorter


  • 0
    J
    class Solution(object):
    def gameOfLife(self, board):
        """
        :type board: List[List[int]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        m,n=len(board),len(board[0])
        for i in xrange(m):
            for j in xrange(n):
                if board[i][j]==0:
                    if self.con(board,i,j)==3:
                        board[i][j]=2
                    else:
                        board[i][j]=0
                elif board[i][j]==1:
                    if self.con(board,i,j)>=2 and self.con(board,i,j)<=3:
                        board[i][j]=3
                    else:
                        board[i][j]=1
        for i in xrange(m):
            for j in xrange(n):
                board[i][j]>>=1
    def con(self,board,i,j):
        m,n=len(board),len(board[0])
        c=0
        if 0<=i-1<m and 0<=j-1<n: c+=board[i-1][j-1]&1
        if 0<=i<m and 0<=j-1<n:   c+=board[i][j-1]&1
        if 0<=i-1<m and 0<=j<n:   c+=board[i-1][j]&1
        if 0<=i-1<m and 0<=j+1<n: c+=board[i-1][j+1]&1
        if 0<=i<m and 0<=j+1<n:   c+=board[i][j+1]&1
        if 0<=i+1<m and 0<=j-1<n: c+=board[i+1][j-1]&1
        if 0<=i+1<m and 0<=j+1<n: c+=board[i+1][j+1]&1
        if 0<=i+1<m and 0<=j<n:   c+=board[i+1][j]&1
        return c

Log in to reply
 

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