题目链接:https://leetcode-cn.com/problems/game-of-life/
题目描述
根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。
给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律:
1.如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
2.如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
3.如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
4.如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
根据当前状态,写一个函数来计算面板上所有细胞的下一个(一次更新后的)状态。下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。
第一次编辑代码:
class Solution {
public void gameOfLife(int[][] board) {
int row = board.length;
int col = board[0].length;
int[][] rt = new int[row][col];
for(int i = 0;i < row;i++)
for(int j = 0;j < col;j++){
setlife(board,rt,i,j,row,col);
}
for(int i = 0;i < row;i++)
for(int j = 0;j < col;j++){
board[i][j] = rt[i][j];
}
}
public void setlife(int[][] b,int[][] r,int i,int j,int row,int col){
int alive = 0;
if(i - 1 >= 0 && j - 1 >= 0 && b[i-1][j-1] == 1)
alive++;
if(i - 1 >= 0 && b[i-1][j] == 1)
alive++;
if(i - 1 >= 0 && j + 1 < col && b[i-1][j+1] == 1)
alive++;
if(j - 1 >= 0 && b[i][j-1] == 1)
alive++;
if(j + 1 < col && b[i][j+1] == 1)
alive++;
if(i + 1 < row && j - 1 >= 0 && b[i+1][j-1] == 1)
alive++;
if(i + 1 < row && b[i+1][j] == 1)
alive++;
if(i + 1 < row && j + 1 < col && b[i+1][j+1] == 1)
alive++;
if(alive < 2 && b[i][j] == 1)
r[i][j] = 0;
else if(alive >= 2 && alive <= 3 && b[i][j] == 1)
r[i][j] = 1;
else if(alive > 3 && b[i][j] == 1)
r[i][j] = 0;
else if(alive == 3 && b[i][j] == 0)
r[i][j] = 1;
}
}
提交结果
ohhhhhhhhhhh
原来大家都是0ms,那没事了