题目描述
在coner题解基础上把循环去掉,双百
C++ 代码
class Solution {
public:
int dx[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
int dy[8] = {1, 1, 1, 0, -1, -1, -1, 0};
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
if(m == 0)
return;
int n = board[0].size();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
int neighbour = 0;//记录周围八个网格的活细胞数
for (int k = 0; k < 8; k ++)
{
int di = dx[k], dj = dy[k];
if(i + di >= 0 && i + di < m && j + dj >= 0 && j + dj < n &&!(di == 0 && dj == 0))
neighbour += board[i+di][j+dj] & 1;
}
if(board[i][j] == 1)
{
if(neighbour < 2 || neighbour > 3)
board[i][j] = 1;//更新后状态为0,所以记为01(二进制)
else
board[i][j] = 3;//更新后状态为1,所以记为11(二进制)
}
else
{
if(neighbour == 3)
board[i][j]=2;//更新后状态为1,所以记为10(二进制)
else
board[i][j] = 0;//更新后状态为0,所以记为00(二进制)
}
}
}
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
board[i][j] =(board[i][j] & 2) >> 1;//取每个网格的第二位,得到更新后状态
}
}
}
};