傳送門
複製原數組模擬
class Solution
{
public:
int index1[8]={1,1,1,0,0,-1,-1,-1};
int index2[8]={0,1,-1,1,-1,-1,0,1};
bool isLegal(int x,int y,int boundx,int boundy)
{
if(x<0||y<0||x==boundx||y==boundy)
{
return false;
}
else
{
return true;
}
}
int choice(int xx,int yy,int boundx,int boundy,vector<vector<int>>& board)
{
int count=0;
for(int u=0;u<8;u++)
{
int x=xx+index1[u];
int y=yy+index2[u];
if(isLegal(x,y,boundx,boundy)&&board[x][y]==1)
{
count++;
}
}
if(count<2&&board[xx][yy]==1)
{
return -1;
}
if(count>3&&board[xx][yy]==1)
{
return 0;
}
if(count==3&&board[xx][yy]==0)
{
return 1;
}
return 2;
}
void gameOfLife(vector<vector<int>>& board)
{
vector<vector<int> > re=board;
int boundx=board.size();
int boundy=board[0].size();
for(int i=0;i<boundx;i++)
{
for(int j=0;j<boundy;j++)
{
int temp=choice(i,j,boundx,boundy,board);
if(temp==-1||temp==0)
{
re[i][j]=0;
}
if(temp==1)
{
re[i][j]=1;
}
}
}
board=re;
}
};