问题描述:LeetCode 289—Game of Life
实现代码:
public class Problem289 {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
// 参考 https://discuss.leetcode.com/topic/65416/sharing-my-java-0ms-solution-o-1-extra-space
public void gameOfLife(int[][] board) {
int height = board.length;
if (height==0) return;
int width = board[0].length;
if (width==0) return;
for (int i=0; i<height; i++) {
int memo1 = 0, memo2 = 0;
for (int j=0; j<width; j++) {
int cur = board[i][j], next=0, life = memo1+memo2;
memo1 = memo2;
memo2 = 0;
if (j==0) { //first cell in a row, no memo
if (i>0) {
memo1 += board[i-1][j] & 1; //top
}
if (i<height-1) {
memo1 += board[i+1][j]; //bottom
}
life+=memo1;
}
memo1+=cur;
if (j<width-1) {
life+= board[i][j+1]; //right
if (i>0) memo2+=board[i-1][j+1] & 1; //right top
if (i<height-1) memo2+=board[i+1][j+1]; //right bottom
}
life+=memo2;
//next state
if (life==3) next = 1;
else if (life==2) next = cur;
else next = 0;
//set merged state
board[i][j] = (next<<1) + cur;
}
}
//set state for next generation
for (int i=0; i<height; i++) for (int j=0; j<width; j++) board[i][j] = board[i][j]>>1;
}
}