思路:用count记录每个ceil四面八方live ceil的数目,然后根据count的值决定当前ceil是1还是0
注意:这里要用一个新数组newBroad来保存当前ceil的新值,不能在broad上进行
注意:这里要用一个新数组newBroad来保存当前ceil的新值,不能在broad上进行
代码:
public class Solution {
public void gameOfLife(int[][] board) {
int m = board.length; //行数
int n = board[0].length; //列数
int[][] newBoard = new int[m][n];
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
int count = 0; //周围活细胞的数目
if(j+1 <= n-1) {
if(board[i][j+1] == 1) count++; //右
if(i-1 >=0 && board[i-1][j+1] == 1) count++; //右上
if(i+1 <= m-1 && board[i+1][j+1] == 1) count++; //右下
}
if(j-1 >= 0) {
if(board[i][j-1] == 1) count++; //左
if(i-1 >= 0 && board[i-1][j-1] == 1) count++; //左上
if(i+1 <= m-1 && board[i+1][j-1] == 1) count++; //左下
}
if(i-1 >= 0 && board[i-1][j] == 1) count++; //上
if(i+1 <= m-1 && board[i+1][j] == 1) count++;
if(board[i][j] == 1 && (count < 2 || count > 3))
newBoard[i][j] = 0;
if(board[i][j] == 0 && count == 3)
newBoard[i][j] = 1;
if(board[i][j] == 1 && (count == 2 || count == 3))
newBoard[i][j] = 1;
}
}
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
board[i][j] = newBoard[i][j];
}
}