这道题仔细看懂题发现不难,注意每个细胞都是同时死或者生的,不能更新局部,必须要全局,于是就想出了用个新的培养细胞的板子newboard,来存放下一次状态的细胞。
public class Solution {
public void gameOfLife(int[][] board) {
int []dx = {0,0,1,1,-1,-1,1,-1};
int []dy = {1,-1,1,-1,1,-1,0,0};
int rows = board.length;
int cols = board[0].length;
if(rows==0||cols==0)return;
int x=0,y=0;
int count =0;
int[][] newboard = new int[rows][cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
count = 0;
for(int k=0;k<8;k++){
x=j+dx[k];
y=i+dy[k];
if(x>=0&&x<cols&&y>=0&&y<rows&&(board[y][x] == 1)){
count++;
}
}
if(board[i][j]==1&&count<=3&&count>=2)newboard[i][j]=1;
else if(board[i][j]!=1&&count==3)newboard[i][j]=1;
else if(board[i][j]==1&&count<2){
newboard[i][j]=0;
}
}
}
for(int i=0;i<rows;i++)
for(int j=0;j<cols;j++)
board[i][j]=newboard[i][j];
}
}