题目
点击查看原题
思路
遍历每一个网格点,同时额外写一个辅助函数查看这个网格点周围有几个活细胞;
分情况讨论就OK了
代码
class Solution {
public:
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
int findCnt(int x, int y, vector<vector<int>>& board1){
int row = board1.size(), col = board1[0].size(), ans = 0;
for(int k = 0; k < 8; k ++){
int x0 = x + dx[k], y0 = y + dy[k];
if(x0 < 0 || x0 >= row || y0 < 0 || y0 >= col) continue;
if(board1[x0][y0] == 1) ans++;
}
return ans;
}
void gameOfLife(vector<vector<int>>& board) {
vector<vector<int>> ans = board;
for(int i = 0; i < board.size(); i ++){
for(int j = 0; j < board[0].size(); j ++){
int temp = findCnt(i, j, board);
if(board[i][j] == 0 && temp == 3) ans[i][j] = 1;
else if(board[i][j] == 1 && (temp < 2) || temp > 3) ans[i][j] = 0;
}
}
board = ans;
}
};