A in-place C solution


  • 0
    G
    class Solution 
    {
    public:
    	bool check(vector<vector<int>>& board, int i, int j)
    	{
    		return (board.size()>0 && i>=0 && j>=0 && i<board.size() && j<board[0].size());
    	}
    	
        void gameOfLife(vector<vector<int>>& board) 
    	{
    		for(int i=0;i<board.size();i++)
    		{
    			for(int j=0;j<board[i].size();j++)
    			{
    				// check the reproduced ones
    				if(board[i][j]==0)
    				{
    					int c=0;
    					if(check(board, i-1,j-1) && board[i-1][j-1]==1) c++;
    					if(check(board, i-1,j) && board[i-1][j]==1) c++;
    					if(check(board, i-1,j+1) && board[i-1][j+1]==1) c++;
    					if(check(board, i,j-1) && board[i][j-1]==1) c++;
    					if(check(board, i,j+1) && board[i][j+1]==1) c++;
    					if(check(board, i+1,j-1) && board[i+1][j-1]==1) c++;
    					if(check(board, i+1,j) && board[i+1][j]==1) c++;
    					if(check(board, i+1,j+1) && board[i+1][j+1]==1) c++;
    
    					if(c==3) board[i][j]=2;
    				}
    			}
    		}
    
    		for(int i=0;i<board.size();i++)
    		{
    			for(int j=0;j<board[i].size();j++)
    			{
    				// check the populated ones
    				if(abs(board[i][j])==1)
    				{
    					int c=0;
    					if(check(board, i-1,j-1) && abs(board[i-1][j-1])==1) c++;
    					if(check(board, i-1,j) && abs(board[i-1][j])==1) c++;
    					if(check(board, i-1,j+1) && abs(board[i-1][j+1])==1) c++;
    					if(check(board, i,j-1) && abs(board[i][j-1])==1) c++;
    					if(check(board, i,j+1) && abs(board[i][j+1])==1) c++;
    					if(check(board, i+1,j-1) && abs(board[i+1][j-1])==1) c++;
    					if(check(board, i+1,j) && abs(board[i+1][j])==1) c++;
    					if(check(board, i+1,j+1) && abs(board[i+1][j+1])==1) c++;
    
    					if(c>3) board[i][j]=-1;
    				}
    			}
    		}
    
    		for(int i=0;i<board.size();i++)
    		{
    			for(int j=0;j<board[i].size();j++)
    			{
    				// check the starved ones
    				if(board[i][j]==1)
    				{
    					int c=0;
    					if(check(board, i-1,j-1) && abs(board[i-1][j-1])==1) c++;
    					if(check(board, i-1,j) && abs(board[i-1][j])==1) c++;
    					if(check(board, i-1,j+1) && abs(board[i-1][j+1])==1) c++;
    					if(check(board, i,j-1) && abs(board[i][j-1])==1) c++;
    					if(check(board, i,j+1) && abs(board[i][j+1])==1) c++;
    					if(check(board, i+1,j-1) && abs(board[i+1][j-1])==1) c++;
    					if(check(board, i+1,j) && abs(board[i+1][j])==1) c++;
    					if(check(board, i+1,j+1) && abs(board[i+1][j+1])==1) c++;
    
    					if(c<2) board[i][j]=-1;
    				}
    			}
    		}
    
    		for(int i=0;i<board.size();i++)
    		{
    			for(int j=0;j<board[i].size();j++)
    			{
    				if(board[i][j]==-1)
    				{
    					board[i][j]=0;
    				}
    
    				if(board[i][j]==2)
    				{
    					board[i][j]=1;
    				}
    			}
    		}
        }
    };

Log in to reply
 

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