时间复杂度O(Mn)
public void gameOfLife(int[][] board)
{
if(board.length == 0 || board[0].length==0) return;
int m = board.length, n = board[0].length;
int[] neighbor = {0, 1, -1};
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(board[i][j] % 10 == 1)
for(int k = 0; k < 3; k++)
for(int l = 0; l < 3; l++)
{
int left = i + neighbor[k];
int right = j + neighbor[l];
if(neighbor[k] == 0 && neighbor[l] == 0)
continue;
if(left >= 0 && right >= 0 && left < m && right < n)
board[left][right] += 10;
}
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(board[i][j] == 21 || board[i][j] == 31)
board[i][j] = 1;
else if(board[i][j] == 30)
board[i][j] = 1;
else
board[i][j] = 0;
}
自己实现:时间复杂度O(n**2)
public static void gameOfLife(int[][] board) {
int r=board.length;
int c=board[0].length;
/*if(c==0)
return;*/
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
//别忘记前提条件在什么时候才会影响周围的数字
if (board[i][j] %10==1 ) {//由于后面的数字被影响过了,所以判断个位是否为1
for (int m = -1; m < 2; m++) {
if(i+m<0||i+m>=r)
continue;
for (int n = -1; n < 2 ; n++) {
if(m==0&&n==0||j+n<0||j+n>=c)
continue;
board[i+m][j+n]+=10;
}
}
//注意在这里并不可获取到所有更新后的值
//System.out.print(board[i][j]+"\t");
}
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.print(board[i][j]+"\t");
}
System.out.println();
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
int value=board[i][j];
if((value%10==1&&(value/10==2)) ||(value/10==3)){
board[i][j]=1;
}
else board[i][j]=0;
}
}