Thinking process

using a higher position bit to represent the next status, and then shift every cell to right

public class Solution {
    public void gameOfLife(int[][] board) {
        int n = board.length;
        if (n == 0) return;
        int m = board[0].length;

        int[] dx = {-1, -1, -1, 0, 1, 1, 1, 0};
        int[] dy = {-1, 0, 1, 1, 1, 0, -1, -1};

        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                int count = 0;
                for (int k = 0; k < dx.length; ++k) {
                    int nx = i + dx[k];
                    int ny = j + dy[k];

                    if (nx >= 0 && ny >= 0 && nx < n && ny < m && (board[nx][ny] & 1) == 1) {
                        count++;
                    }
                }

                if ((board[i][j] & 1) == 1) {
                    if (count == 2 || count == 3) {
                        board[i][j] |= board[i][j] << 1;
                    }
                } else {
                    if (count == 3) {
                        board[i][j] |= 1 << 1;
                    }
                }
            }
        }

        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                board[i][j] = board[i][j] >> 1;
            }
        }
    }
}

results matching ""

    No results matching ""