Java In-place Solution


  • 1
    M
        public void gameOfLife(int[][] board) {
            if (board == null || board.length == 0) return;
            int m = board.length, n = board[0].length;
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    int cnt = 0;
                    for (int di = -1; di <= 1; ++di) {
                        for (int dj = -1; dj <= 1; ++dj) {
                            if (di == 0 && dj == 0) continue;
                            int x = i + di, y = j + dj;
                            if (x >= 0 && x < m && y >= 0 && y < n && (board[x][y] & 1) == 1) ++cnt;
                        }
                    }
                    if (board[i][j] == 1) {
                        if (cnt == 2 || cnt == 3) board[i][j] = 3;
                    } else {
                        if (cnt == 3) board[i][j] = 2;
                    }
                }
            }
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    board[i][j] >>= 1;
                }
            }
        }
    

Log in to reply
 

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