C++ in-place solution


  • 0
    J

    The code below simply stores the number of 1s in each cell. If the cell is live, the stored value is positive. If the cell is dead, the stored value is negative.

    void updateCell(vector<vector<int>>& board, int row, int col) {
    	int numOfLiveCells = board[row][col];
    
    	if (row - 1 >= 0 && col - 1 >= 0 && board[row - 1][col - 1] > 0)
    		numOfLiveCells++;
    	if (row - 1 >= 0 && board[row - 1][col] > 0)
    		numOfLiveCells++;
    	if (row - 1 >= 0 && col + 1 < board[row].size() && board[row - 1][col + 1] > 0)
    		numOfLiveCells++;
    	if (col + 1 < board[row].size() && board[row][col + 1] > 0)
    		numOfLiveCells++;
    	if (row + 1 < board.size() && col + 1 < board[row].size() && board[row + 1][col + 1] > 0)
    		numOfLiveCells++;
    	if (row + 1 < board.size() && board[row + 1][col] > 0)
    		numOfLiveCells++;
    	if (row + 1 < board.size() && col - 1 >= 0 && board[row + 1][col - 1] > 0)
    		numOfLiveCells++;
    	if (col - 1 >= 0 && board[row][col - 1] > 0)
    		numOfLiveCells++;
    
    	board[row][col] = board[row][col] == 1 ? numOfLiveCells : -numOfLiveCells;
    }
    
    void gameOfLife(vector<vector<int>>& board) {
    	for (int i = 0; i<board.size(); i++) {
    		for (int j = 0; j<board[i].size(); j++)
    			updateCell(board, i, j);
    	}
    
    	for (int i = 0; i<board.size(); i++) {
    		for (int j = 0; j<board[i].size(); j++) {
    			if (board[i][j] > 0) {
    				if (board[i][j] - 1 < 2 || board[i][j] - 1 > 3)
    					board[i][j] = 0;
    				else
    					board[i][j] = 1;
    			}
    			else {
    				if (board[i][j] == -3)
    					board[i][j] = 1;
    				else
    					board[i][j] = 0;
    			}
    		}
    	}
    }

Log in to reply
 

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