# 每天一道LeetCode-----生命游戏

## Game of Life

• 对于一个live的细胞，如果它周围live的细胞数量是两个或三个，那么它继续live

class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
//2 : current is live and next is live
//3 : current is live but next is dead
//4 : current is dead but next is live

if(board.empty() || board[0].empty())
return;
int m = board.size();
int n = board[0].size();
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
int liveCount = 0;
/* 判断周围live的细胞数量 */
for(int p = std::max(0, i - 1); p < std::min(m, i + 2); ++p)
{
for(int q = std::max(0, j - 1); q < std::min(n, j + 2); ++q)
{
if(p == i &&  q == j)
continue;
if(isLive(board, p, q))
++liveCount;
}
}

/* 根据周围细胞数量改变状态 */
if(liveCount < 2 && isLive(board, i, j))
board[i][j] = 3;
else if(liveCount > 3 && isLive(board, i, j))
board[i][j] = 3;
else if(liveCount == 3 && !isLive(board, i, j))
board[i][j] = 4;
}
}

/* 第二次遍历时改变状态 */
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
if(board[i][j] == 3)
board[i][j] = 0;
else if(board[i][j] == 4)
board[i][j] = 1;
}
}
}

private:
/* 一个细胞处于live的条件是当前状态是live而不是下一个状态是live */
bool isLive(vector<vector<int>>& board, int i, int j)
{
return board[i][j] == 1 || board[i][j] == 2 || board[i][j] == 3;
}
};


• 0011表示当前状态是live并且下一个状态是live，值为3

class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
if(board.empty() || board[0].empty())
return;
int m = board.size();
int n = board[0].size();
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
int liveCount = 0;
for(int p = std::max(0, i - 1); p < std::min(m, i + 2); ++p)
{
for(int q = std::max(0, j - 1); q < std::min(n, j + 2); ++q)
{
/* 这里没有排除p == i && q == j */
liveCount += (board[p][q] & 1);
}
}
/* 对于live的细胞，它下一个状态仍然是live的条件是算上它本身，周围live的细胞数量是3或4个 */
if(liveCount == 3 || liveCount - board[i][j] == 3)
board[i][j] |= 2;
}
}
for(int i = 0; i < m; ++i)
{
for(int j = 0; j < n; ++j)
{
board[i][j] >>= 1;
}
}
}
};