Very concise Java solution with mod operations


  • 1
    A
    public void gameOfLife(int[][] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                int sum = 0;
                for (int klo = Math.max(i-1,0); klo < Math.min(i+2,board.length); klo++) 
                    for (int llo = Math.max(j-1,0); llo < Math.min(j+2,board[0].length); llo++) 
                        if (!(klo == i && llo == j)) sum += board[klo][llo] % 2;
                if (board[i][j] % 2 == 0 && sum == 3) board[i][j] = 2;
                else if (board[i][j] % 2 == 1 && sum < 2 
                        || board[i][j] % 2 == 1 && sum > 3) board[i][j] = 3;
            }
        }
        for (int i = 0; i < board.length; i++) 
            for (int j = 0; j < board[0].length; j++) 
                board[i][j] = Math.min(board[i][j] % 3, 1);
    }

Log in to reply
 

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