您的位置:首页 > Web前端

289. Game of Life

2016-09-25 16:57 246 查看
主要难点在于inplace,解决办法:

用4种特殊state标记,同时记录下current state和next state。

标记如下:

00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live;

tips:必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态

代码如下:

public class Solution {
public int f(int i, int j, int[][] board){
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length){
return -1;
}else{
return board[i][j];
}
}

public int liveNum(int i, int j, int[][] board){
int count = 0;
int[][] offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1}};
for (int[] offset : offsets){
if (f(i + offset[0], j + offset[1], board) % 2 == 1)
count ++;
}
return count;
}

//00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live;
//必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态
public void gameOfLife(int[][] board) {
if (board.length == 0 || board[0].length == 0)
return;
int count;
for(int i = 0; i < board.length; i ++){
for(int j = 0; j < board[0].length; j ++){
count = liveNum(i, j, board);
if (board[i][j] % 2 == 1){  //live cell
if (count == 2 || count == 3)
board[i][j] += 2;
}else{
if (count == 3){
board[i][j] += 2;
}
}
}
}
for(int i = 0; i < board.length; i ++){
for(int j = 0; j < board[0].length; j ++){
board[i][j] = board[i][j] / 2;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: