分析:这道题起初自己搞复杂了,我原先以为是求最后的稳态,即一个状态再跳转到另外一个状态时,两个矩阵是一样的。但是有个测试用例是:
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
这个测试用例会发现该初始值根本就没有稳态,这才注意到是求的下一个状态。
然后这个题的难点就在于了如何在in-place里面存储改变后的值?(特别是followup中的,每次状态都会同时改变)。那就自定义了若干变量值,然后再修复即可
代码如下:1ms
public class Solution {
private int countLiveNeigh(int[][] board,int row,int col){
int count = 0;
for(int i = row-1;i<=row+1;i++){
for(int j = col-1;j<=col+1;j++){
if(i==row && j==col)
continue;
if(i>=0 && i<board.length && j>=0 && j<board[0].length && (board[i][j]==1||board[i][j]==2))//最开始状态为1的
count++;
}
}
return count;
}
public void gameOfLife(int[][] board) {
/*
* 0:0--->0
1:1--->1
2:1--->0
3:0--->1
*/
int rowlen = board.length;
int collen = board[0].length;
for(int row = 0;row<rowlen;row++){
for(int col = 0;col<collen;col++){
int count = countLiveNeigh(board,row,col);
if(count == 2);
else if(count == 3){
board[row][col] = board[row][col]==0?3:1;
}else{
board[row][col] = board[row][col]==1?2:0;
}
}
}
for(int row = 0;row<rowlen;row++){
for(int col = 0;col<collen;col++){
board[row][col] %= 2;
}
}
}
}