死->活:-1,死->死:0,活->活:1,活->死:2
这样就可以同时存储变化前后的状态了。
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
for(int i=0;i<board.size();++i)
for(int j=0;j<board[0].size();++j)
_gameOfLife(board,i,j);
for(int i=0;i<board.size();++i)
for(int j=0;j<board[0].size();++j){
if(board[i][j] == 2)
board[i][j] = 0;
else if(board[i][j] == -1)
board[i][j] = 1;
}
}
void _gameOfLife(vector<vector<int>>& board,int x,int y) {
int live = 0;
if(x>0)
{
if(board[x-1][y]>0)//左
++live;
if(y>0 && board[x-1][y-1]>0)//左上
++live;
if(y<board[0].size()-1 && board[x-1][y+1]>0)//左下
++live;
}
if(x<board.size()-1)
{
if(board[x+1][y]>0)//右
++live;
if(y>0 && board[x+1][y-1]>0)//右上
++live;
if(y<board[0].size()-1 && board[x+1][y+1]>0)//右下
++live;
}
if(y >0 && board[x][y-1]>0)//上
++live;
if(y < board[0].size()-1 && board[x][y+1]>0)//下
++live;
if(board[x][y] == 1)
{
if(live<2||live>3)
board[x][y] = 2;
}
else if(live == 3)
board[x][y] = -1;
}
};