题目:
According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population…
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.
个人觉得这道题还算简单,可能唯一的难点在于不适用额外的空间这一点,因此我添加了两种额外的状态 -1 和 2 ,-1表示活->死,2表示死->活
代码如下:
class Solution {
public:
void isAlive(vector<vector<int>>& board, int i, int j){
int live_neighbors = 0;
//等于-1表示上一状态是活的,等于2表示上一状态是死亡的
if(i > 0 and j > 0 and abs(board[i-1][j-1]) == 1)live_neighbors++;
if(i > 0 and abs(board[i-1][j]) == 1)live_neighbors++;
if(i > 0 and j < board[0].size()-1 and abs(board[i - 1][j + 1]) == 1)live_neighbors++;
if(j < board[0].size()-1 and abs(board[i][j + 1]) == 1)live_neighbors++;
if(i < board.size()-1 and j < board[0].size()-1 and (board[i + 1][j + 1]) == 1)live_neighbors++;
if(i < board.size()-1 and abs(board[i + 1][j]) == 1)live_neighbors++;
if(i < board.size()-1 and j > 0 and abs(board[i + 1][j - 1]) == 1)live_neighbors++;
if(j > 0 and abs(board[i][j - 1]) == 1)live_neighbors++;
if(board[i][j] == 0){
if(live_neighbors == 3)board[i][j] = 2;
}
else
{
if(live_neighbors < 2 or live_neighbors > 3)board[i][j] = -1;
}
}
void gameOfLife(vector<vector<int>>& board) {
for(auto i = 0; i< board.size(); i++)
for(auto j = 0; j< board[0].size(); j++)
isAlive(board, i, j);
for(auto i = 0; i< board.size(); i++)
for(auto j = 0; j< board[0].size(); j++){
if(board[i][j] > 0)board[i][j] = 1;
else board[i][j] = 0;
}
}
};