Show my solution with extra space in Java, just help to understand "the board needs to be updated at the same time"


  • 1
    K
    public class Solution {
    public void gameOfLife(int[][] board) {
        int row = board.length;
        int col = board[0].length;
        int countlives=0;
        int[][] change = new int[row][col];
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<col;j++)
            {
            	countlives=0;
                for(int p=Math.max(i-1,0);p<Math.min(i+2,row);p++)
                {
                    for(int q = Math.max(j-1,0);q<Math.min(j+2,col);q++)
                    {
                        if(board[p][q]==1) countlives++;
                    }
                }
                countlives = countlives - board[i][j];
                if(countlives>3||countlives<2) change[i][j]=0;
                if(countlives==3) change[i][j] = 1;
                if(countlives==2) change[i][j] = board[i][j];
            }
        }
        System.arraycopy(change,0,board,0,board.length);
    }
    

    }


Log in to reply
 

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