算法
用到了位运算 ,原地更新就是在原数组更新,
二进制10表示由0变成1,即10进制2
二进制11 表示由1变成1 ,即10进制3
二进制01表示由1变成0,即10进制1
最后只要输出左边的1位即可,可以用位运算>>1加快效率
C++ 代码
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
if (m==0) return;
int n = board[0].size();
int new_x, new_y, live;
int dx[] = {-1,-1,-1, 0, 1, 1, 1, 0 };
int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1};
for (int i=0; i<m; i++)
for (int j=0; j<n; j++) {
live = 0;
for (int k=0; k<8; k++){
new_x = i+dx[k];
new_y = j + dy[k];
if (new_x >= 0 and new_x < m and new_y >=0 and new_y < n) {
if (board[new_x][new_y] & 1) live++;
}
}
if (board[i][j] & 1 and live < 2 ) board[i][j] = 1;
if (board[i][j] & 1 and (live == 2 || live == 3 )) board[i][j] = 3;
if (board[i][j] & 1 and live > 3) board[i][j] = 1;
if (!(board[i][j] & 1) and live == 3 ) board[i][j] = 2;
}
for (int i=0; i<m; i++)
for (int j=0; j<n; j++)
board[i][j] = board[i][j] >> 1;
}
};