题目大意:
活细胞:2个或3个活的邻域则存活,否则死掉。
死细胞:3个活的邻域,则变为活细胞。
原地转换,下面的代码并没有逐个细胞统计邻居数,而是将每个活细胞的信号(+=2)加到周边细胞上,因为数组是int型,所以利用除了最低位(标志现在的状态)的位保存个数,最后将数组元素右移一位就是统计的数字了。
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
if (board.empty()) return;
m = board.size();
n = board[0].size();
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] & 1) {
add_(board, i - 1, j - 1);
add_(board, i , j - 1);
add_(board, i + 1, j - 1);
add_(board, i + 1, j);
add_(board, i + 1, j + 1);
add_(board, i, j + 1);
add_(board, i - 1, j);
add_(board, i - 1, j + 1);
}
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int t = board[i][j] >> 1;
if ((board[i][j] & 1 && t == 2) || (t == 3)) {
board[i][j] = 1;
} else board[i][j] = 0;
}
}
}
private:
int m,n;
inline void add_(vector<vector<int>>& board, int i, int j) {
if (i < 0 || i == m || j < 0 || j == n) return;
board[i][j] += 2;
}
};