给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞
(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律:
如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
根据当前状态,写一个函数来计算面板上所有细胞的下一个(一次更新后的)状态。下一个状态是通过将上述规则同时
应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。
输入:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
输出:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/game-of-life
class Solution {
public void gameOfLife(int[][] board) {
int row = board.length;
int col = board[0].length;
int[] neighbour = {0,1,-1};
int[][] res = new int[row][col];
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
res[i][j] = board[i][j];
}
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
int count = 0;
for(int r=0;r<3;r++){
for(int c=0;c<3;c++){
if(!(neighbour[r]==0 && neighbour[c]==0)){
int m = i + neighbour[r];
int n = j + neighbour[c];
if((m<row && m>=0)&&(n<col&&n>=0)&&(res[m][n]==1)){
count++;
}
}
}
}
if(res[i][j] == 1 && (count<2 || count >3)){
board[i][j] = 0;
}
if(res[i][j] == 0 && (count == 3)){
board[i][j] = 1;
}
}
}
}
}
- 但是上面这个代码的空间复杂度比较高,O(mn),所以我们也可以像下面这种写法,如果细胞原来是活的,然后根据规则会变为死细胞的话,我们就将其的状态更新为-1,注意,这里更新为-1是因为根据题目要求,我们要做到整个矩阵的同步更新,所以将原来的1变为-1,最后只用Math.abs(),对结果是没有影响的; 同样,如果原来的细胞就是死细胞,根据规则变成活细胞之后就将原来的状态更新为2,这里更新为2也是为了之后对整个矩阵的遍历过程中不产生影响。
class Solution {
public void gameOfLife(int[][] board) {
int[] neighbors = {0, 1, -1};
int rows = board.length;
int cols = board[0].length;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (!(neighbors[i] == 0 && neighbors[j] == 0)) {
int r = (row + neighbors[i]);
int c = (col + neighbors[j]);
if ((r < rows && r >= 0) && (c < cols && c >= 0) && (Math.abs(board[r][c]) == 1)) {
count++;
}
}
}
}
if ((board[row][col] == 1) && (count < 2 || count > 3)) {
board[row][col] = -1;
}
if (board[row][col] == 0 && count == 3) {
board[row][col] = 2;
}
}
}
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (board[row][col] > 0) {
board[row][col] = 1;
} else {
board[row][col] = 0;
}
}
}
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/game-of-life/solution/sheng-ming-you-xi-by-leetcode-solution/