Game of Life (Leetcode 289)

Problem Link: https://leetcode.com/problems/game-of-life/

This problem can be done using an extra matrix very easily. But, the below method does in-place operations without using extra space.

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        def countNeighbours(board,i,j,m,n):
            
            nei=0
            l=i-1
            r=i+1
            t=j-1
            b=j+1
            if(l<0):
                l=l+1
            if(t<0):
                t=t+1
            if(r==m):
                r=r-1
            if(b==n):
                b=b-1
            for fp in range(l,r+1):
                for sp in range(t,b+1):
                    if(fp==i and sp==j):
                        continue
                    else:
                        if(board[fp][sp]==1 or board[fp][sp]==-1):
                            nei+=1

            return nei
        
        
        m=len(board)
        n=len(board[0])
        for i in range(m):
            for j in range(n):
                nei=countNeighbours(board,i,j,m,n)
                # If a cell goes from 1 to 0,
                #       put -1
                # If a cell goes from 0 to 1,
                #       put 2
                if(board[i][j]==1 and nei<2):
                    board[i][j]=-1
                elif(board[i][j]==1 and nei>3):
                    board[i][j]=-1
                elif(board[i][j]==0 and nei==3):
                    board[i][j]=2
        
        for i in range(m):
            for j in range(n):
                if(board[i][j]==-1):
                    board[i][j]=0
                elif(board[i][j]==2):
                    board[i][j]=1   

Last updated