LeetCode 289. 生命游戏
原题链接
中等
作者:
Tracing
,
2020-08-27 14:49:45
,
所有人可见
,
阅读 369
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
if(board.empty()) return;
int n = board.size();
int m = board[0].size();
//8个遍历方向
vector<vector<int>> dires = {{1, 0}, {0,1}, {-1, 0}, {0, -1}, {-1, -1}, {1, 1}, {-1, 1}, {1, -1}};
//标记当前节点是否改变过
vector<vector<bool>> flag(n, vector<bool>(m, false));
//获取一个节点附近的活节点
auto get_sum = [&](int x, int y) {
int sum = 0;
for(const auto& dir : dires) {
auto next_x = x + dir[0];
auto next_y = y + dir[1];
if (next_x < n && next_y < m && next_x >= 0 && next_y >= 0) {
if(board[next_x][next_y] == 1 && flag[next_x][next_y] == false) ++sum;
if(board[next_x][next_y] == 0 && flag[next_x][next_y] == true) ++sum;
}
}
return sum;
};
//遍历整个图
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
auto sum = get_sum(i, j); //当前节点附近的活结点
//根据题目规则写出
if(board[i][j] == 1) {
if(sum < 2 || sum > 3) board[i][j] = 0, flag[i][j] = true;
}
else {
if(sum == 3) board[i][j] = 1, flag[i][j] = true;
}
}
}
}
};