Easy Java solution


  • 0
    J

    Just count the surrounding lives, assume to be count, store (count + 1) * 10 in the cell. If original value is 0, store negative number.

    public void gameOfLife(int[][] board) {
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    int count = 0;
                    int x1 = (i > 0 ? i - 1 : 0);
                    int x2 = (i < board.length -1 ? i + 1 : board.length - 1);
                    int y1 = (j > 0 ? j - 1 : 0);
                    int y2 = (j < board[0].length - 1 ? j + 1 : board[0].length - 1);
                    for (int k = x1; k <= x2; k++) {
                        for (int m = y1; m <= y2; m++) {
                            if ((k != i || m != j) && board[k][m] > 0) count++;
                        }
                    }
                    if (board[i][j] == 0) {
                        board[i][j] = 0 - (count + 1) * 10; 
                    } else {
                        board[i][j] = (count + 1) * 10;
                    }
                }
            }
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    int count = board[i][j] / 10;
                    boolean wasAlive = count > 0;
                    int realCount = count > 0 ? (count - 1) : -(count + 1);
                    if (wasAlive) {
                        if (realCount < 2 || realCount > 3) board[i][j] = 0;
                        else board[i][j] = 1;
                    } else if (realCount == 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.