LeetCode – Game of Life (Java)

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules:


Write a function to compute the next state (after one update) of the board given its current state.

Java Solution 1

Because we need to solve the problem in place, we can use the higher bit to record the next state. And at the end, shift right a bit to get the next state for each cell.

public void gameOfLife(int[][] board) {
    if(board==null || board.length==0||board[0].length==0)
    int m=board.length;
    int n=board[0].length;
    int[] x = {-1, -1, 0, 1, 1, 1, 0, -1};
    int[] y = {0, 1, 1, 1, 0, -1, -1, -1};
            int count=0;
                int nx=i+x[k];
                int ny=j+y[k];
            //<2 die
                board[i][j] &= 1;
            //same state
                board[i][j] |=  board[i][j]<<1;
            //go live
                board[i][j] |=2;
            //>3 die
                board[i][j] &=1;
            board[i][j] = board[i][j]>>1;
Category >> Algorithms  
String foo = "bar";