2024每日刷题(126)
Leetcode—289. 生命游戏
算法思想
实现代码
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int rows = board.size();
int cols = board[0].size();
int neighbors[3] = {0, 1, -1};
vector<vector<int>> copyBoard(rows, vector<int>(cols, 0));
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
copyBoard[i][j] = board[i][j];
}
}
int r, c;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
int liveNum = 0;
for(int row = 0; row < 3; row++) {
for(int col = 0; col < 3; col++) {
if(!(neighbors[row] == 0 && neighbors[col] == 0)) {
r = i + neighbors[row];
c = j + neighbors[col];
if((r >= 0 && r < rows) && (c >= 0 && c < cols) &&(copyBoard[r][c] == 1)) {
liveNum++;
}
}
}
}
// 条件1、3
if((board[i][j] == 1) && (liveNum < 2 || liveNum > 3)) {
board[i][j] = 0;
}
// 条件4
if(board[i][j] == 0 && liveNum == 3) {
board[i][j] = 1;
}
}
}
}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!