public class ShowMeBug {
public final int[][] arr;
public ShowMeBug(int[][] arr) {
this.arr = arr;
}
public static void main(String[] args) {
int[][] arr = new int[][]{
{0, 0, 0},
{1, 1, 1},
{0, 0, 0}
};
final ShowMeBug showMeBug = new ShowMeBug(arr);
showMeBug.updateNextState(arr);
showMeBug.printState();
}
/**
* 输出当前生存状态到控制台
*
*/
public void printState() {
int M = arr.length;
int N = arr[0].length;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
System.out.print(arr[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
/**
* 更新arr下个tick的生存状态
*
* @param arr 当前状态下的数组
*/
public void updateNextState(int[][] arr) {
int M = arr.length;
int N = arr[0].length;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
arr[i][j] = getNextVal(arr, i, j);
}
}
}
/**
* 计算某细胞下个tick的状态
*
* @param arr 当前状态下的数组
* @param i 行索引
* @param j 列索引
* @return 生存返回1,否则返回0
*/
private int getNextVal(int[][] arr, int i, int j) {
int nextVal = 0;
//TODO:请完善该函数,要求:需要调用countLivingNeighbors
int count = countLivingNeighbors(arr,i,j);
if(arr[i][j] == 1 && count < 2){
nextVal = 0;
}else if(arr[i][j] == 1 && (count == 2 || count == 3)){
nextVal = arr[i][j];
}else if(arr[i][j] == 1 && count > 3){
nextVal = 0;
}else if(arr[i][j] == 0 && count == 3){
nextVal = 1;
}
return nextVal;
}
/**
* 计算某细胞的存活邻居数量
*
* @param arr 当前状态下的数组
* @param i 行索引
* @param j 列索引
* @return 该元素存活的邻居数量
*/
private int countLivingNeighbors(int[][] arr, int i, int j) {
int count = 0;
//TODO:请完善该函数
int num1 = backtrack(arr,i - 1,j - 1);
int num2 = backtrack(arr,i - 1,j);
int num3 = backtrack(arr,i - 1,j + 1);
int num4 = backtrack(arr,i,j - 1);
int num5 = backtrack(arr,i,j + 1);
int num6 = backtrack(arr,i + 1,j - 1);
int num7 = backtrack(arr,i + 1,j);
int num8 = backtrack(arr,i + 1,j + 1);
return num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8;
}
private int backtrack(int[][] arr,int i,int j){
if(i < 0 || j < 0 || i == arr.length || j == arr[0].length){
return 0;
}
return arr[i][j];
}
}