题目描述:
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.
题目要求在原位操作,空间复杂度为o(1)
思路:
既然要求是原位操作,那么对于状态board[i][j],live->dead,将值1->2,那么当board[I][j]作为其他位置的邻居时,判断是否>=1即可;dead->live,将值0->-1。当所有位置遍历过后,再次遍历所有位置,值为2的位置,说明更新后状态为dead,值改为0;值为-1的位置,说明更新之后状态为live,值改为1.
代码:
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m=board.size();
int n=board[0].size();
if (m==0||n==0)
return;
for (int i=0; i<m; i++)
for (int j=0; j<n; j++)
fun(board,i,j,m,n);
for (int i=0; i<m; i++)
for (int j=0; j<n; j++)
{
if (board[i][j]==2)
board[i][j]=0;
if (board[i][j]==-1)
board[i][j]=1;
}
}
void fun(vector<vector<int>>& board, int i,int j, int m, int n)
{
int count=0;
if (i-1>=0&&board[i-1][j]>=1)
count++;
if (i+1<m&&board[i+1][j]>=1)
count++;
if (j-1>=0&&board[i][j-1]>=1)
count++;
if (j+1<n&&board[i][j+1]>=1)
count++;
if (i-1>=0&&j-1>=0&&board[i-1][j-1]>=1)
count++;
if (i-1>=0&&j+1<n&&board[i-1][j+1]>=1)
count++;
if (i+1<m&&j-1>=0&&board[i+1][j-1]>=1)
count++;
if (i+1<m&&j+1<n&&board[i+1][j+1]>=1)
count++;
if (board[i][j]==1&&(count<2||count>3))
board[i][j]++;
if (board[i][j]==0&&count==3)
board[i][j]--;
}
};