Title Description
solution:
Here to talk about bit-manipulation Kazakhstan:
An int accounted for 32, 0, 1, but only one, we can make use of all the rest of the digits do mark. Specifically, by using only the second can,
. 1 rule : the original 01, the number of viable cells is less than about 2, a right shift is 0
rule 2 : the original 01, the number of viable cells is equal to about 2, or 3,01 or 10 is 11, one is right. 1
rule 3 : the original is 01, the number of surrounding cell survival greater than 3, the right one is 0
rule 4 : the original is 00, equal to the number of cell survival around 3.00 or 10 is 10, is a right one
Really was a god operation! !
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1};
int dy[] = {-1, -1, -1, 0, 0, 1, 1, 1};
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[0].size();j++)
{
int sum = 0;
for(int k=0;k<8;k++)
{
int nx = i + dx[k];
int ny = j + dy[k];
if((nx>=0 && nx<board.size()) && (ny>=0 && ny<board[0].size()))
sum += (board[nx][ny]&1); // 只累加最低位
}
if(board[i][j]==1)
{
if(sum==2 || sum==3) board[i][j] |= 2; // 使用第二个bit标记是否存活
}
else
{
if(sum==3) board[i][j] |= 2;
}
}
}
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[0].size();j++)
board[i][j] >>= 1;
}
}
};