# LeetCode-289 生命游戏

## 题目：

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.

## 解法

void solution::gameOfLife(vector<vector<int>>& board);


“暗示”我们这是一个在原地的修改。但是原地直接从0改到1或者1改到0，那么后面的细胞如果邻域包括被修改的细胞就可能影响当前细胞的下一个状态，因此我们要考虑扩展状态。由于状态间的变化只能有4种情况：
0到1；0到0；1到0；1到1.我们可以将状态扩展为0，1，2，3四个。为了方便状态判断以及后续将状态快速变为0-1的状态，我们可以规定：
0 -> 0 : 0
0 -> 1 : 3
1 -> 0 : 2
1 -> 1 : 1

C++代码如下：

void gameOfLife(vector<vector<int>>& board)
{
// 0 -> 0 : 0
// 0 -> 1 : 3
// 1 -> 0 : 2
// 1 -> 1 : 1
//1 & 2 means this is a live cell in current state
//0 & 3 means this is a dead cell in current state
//0 & 2 means this will be dead in next state
//1 & 3 means this will be live in next state
int rows = board.size(), cols = board[0].size();
vector<int> dr = { -1,-1,-1,0,0,1,1,1 }, dc = { -1,0,1,-1,1,-1,0,1 };
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
int cnt = 0;
for (int k = 0; k < 8; ++k) {
if (i + dr[k] >= 0 && i + dr[k] < rows && j + dc[k] >= 0 && j + dc[k] < cols && (board[i + dr[k]][j + dc[k]] == 1 || board[i + dr[k]][j + dc[k]] == 2)) ++cnt;
}
if (board[i][j] == 1) {
if (cnt < 2 || cnt>3) board[i][j] = 2;
}
else {
if (cnt == 3) board[i][j] = 3;
}
}
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
board[i][j] = board[i][j] % 2;
}
}
}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客