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:
Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population..
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
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) return; 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}; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ int count=0; for(int k=0; k<8; k++){ int nx=i+x[k]; int ny=j+y[k]; if(nx>=0&&nx<m&&ny>=0&&ny<n&&(board[nx][ny]&1)==1){ count++; } } //<2 die if(count<2){ board[i][j] &= 1; } //same state if(count==2||count==3){ board[i][j] |= board[i][j]<<1; } //go live if(count==3){ board[i][j] |=2; } //>3 die if(count>3){ board[i][j] &=1; } } } for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ board[i][j] = board[i][j]>>1; } } } |
public class Solution {
public void gameOfLife(int[][] b) {
if (b == null || b.length == 0) {
return;
}
int[] dx = new int[] {
0,
-1,
-1,
-1,
0,
1,
1,
1
};
int[] dy = new int[] {
-1, -1, 0, 1, 1, 1, 0, -1
};
int m = b.length;
int n = b[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int count = 0;
for (int k = 0; k = 0 && x = 0 && y < n && (b[x][y] & 1) == 1) {
count++;
}
}
if ((b[i][j] & 1) == 1) {
if (count == 2 || count == 3) {
b[i][j] |= 1 << 1;
}
} else {
if (count == 3) {
b[i][j] |= 1 << 1;
}
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j > 1;
}
}
}
}
Thank you. I hope this makes it more readable.
https://uploads.disquscdn.com/images/c741e5f71141bcaf98fc09f06000f5e914dc3114fb9c8acad6fb5fe5828edcf1.png