1.题目
根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。
给定一个包含 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]
]
进阶:
你可以使用原地算法解决本题吗?请注意,面板上所有格子需要同时被更新:你不能先更新某些格子,然后使用它们的更新后的值再更新其他格子。
本题中,我们使用二维数组来表示面板。原则上,面板是无限的,但当活细胞侵占了面板边界时会造成问题。你将如何解决这些问题?
2.1 记录每个需要变化的细胞的位置
对于每个细胞遍历其周围八个细胞,记录活细胞的数量,然后判断其是否需要变化,如果需要则放入list中。
class Solution {
public:
int dx[8] = {-1,-1,-1,0,0,1,1,1};
int dy[8] = {-1,0,1,-1,1,-1,0,1};
int findAlive(vector<vector<int>>& board, int x, int y){
int res = 0;
for(int i = 0; i < 8; i++){
auto cx = x + dx[i], cy = y + dy[i];
if(cx >= 0 && cx < board.size() && cy >= 0 && cy < board[0].size() && board[cx][cy] == 1)
res++;
}
return res;
}
struct node{
int x,y;
node(int x_, int y_) : x(x_), y(y_){}
};
void gameOfLife(vector<vector<int>>& board) {
list<node> Set;
int m = board.size();
if(m <= 0) return;
int n = board[0].size();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int cnt = 0;
cnt = findAlive(board, i, j);
if(board[i][j] == 1){
if(cnt < 2 || cnt > 3){
Set.push_back(node(i,j));
}
}
else{
if(cnt == 3) Set.push_back(node(i,j));
}
}
}
for(auto& it : Set){
board[it.x][it.y] = 1 - board[it.x][it.y];
}
}
};
2.2 原地算法
将需要变化的活细胞标记为2,将需要变化的死细胞标记为-1.
遍历两遍数组。
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int count = 0;
if(i-1 >= 0 && j-1>=0 && board[i-1][j-1]>0) count++;
if(i-1 >= 0 && board[i-1][j]>0) count++;
if(i-1 >= 0 && j+1 < n && board[i-1][j+1]>0) count++;
if(j-1 >= 0 && board[i][j-1] > 0) count++;
if(j+1 < n && board[i][j+1] > 0) count++;
if(i+1 < m && j-1>=0 && board[i+1][j-1] > 0) count++;
if(i+1 < m && board[i+1][j] > 0) count++;
if(i+1 < m && j+1<n && board[i+1][j+1] > 0) count++;
if(board[i][j] > 0){
if(count < 2 || count > 3){
board[i][j] = 2;
}
}
else{
if(count == 3){
board[i][j] = -1;
}
}
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(board[i][j] == 2) {board[i][j] = 0;}
else if(board[i][j] == -1) {board[i][j] = 1;}
}
}
}
};