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.
Example:
Input: [ [0,1,0], [0,0,1], [1,1,1], [0,0,0] ] Output: [ [0,0,0], [1,0,1], [0,1,1], [0,1,0] ]
/* 生命游戏:
* 对于活细胞: 周围(8邻域)有2或者3个或细胞 该细胞生存 否则死亡
* 对于死细胞: 周围有3个活细胞则复活
*
* 该函数对当前状态进行一次更新
* 由于不用额外空间,可以用状态转移表示:(既能完成更新又能得知更新之前的状态) 最后再取余得最终状态(即对于余数为0下一回合都是死, 否则为生)
* 状态:
* 注意0,1未更新前的状态与题目要求一致为0, 1 然后定下2,3状态
* 0 death->death
* 1 live->live
* 2 live->death
* 3 death->live
*
* */
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int row=board.size(), col=board[0].size();
// 定义移动方向的数组 通过x[k] y[k]得到移动方向
int dx[]={0, 0, 1, -1, 1, -1, 1, -1};
int dy[]={1, -1, 0, 0, 1, -1, -1, 1};
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
int cnt=0;// 扫描八邻域统计当前为活的细胞(状态1 2)
for(int k=0;k<8;k++){
int x=i+dx[k], y=j+dy[k];
if(x>=0 && x<row && y>=0 && y<col
&& (board[x][y]==1 || board[x][y]==2)) cnt++;
}
//根据活细胞的个数进行状态转换
if(board[i][j]==0 && cnt==3) board[i][j]=3;
if(board[i][j]==1 && (cnt>3 || cnt<2)) board[i][j]=2;
}
}
// 根据状态得到更新后的结果
for(int i=0;i<row;i++) {
for (int j = 0; j < col; j++) {
board[i][j] %= 2;
}
}
}
};