Leetcode—289. 生命游戏【中等】

2024每日刷题(126)

Leetcode---289. 生命游戏

算法思想

实现代码

cpp 复制代码
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;
                }
            }
        }
    }
};

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
NAGNIP1 小时前
一文搞懂树模型与集成模型
算法·面试
NAGNIP1 小时前
万字长文!一文搞懂监督学习中的分类模型!
算法·面试
技术狂人1681 小时前
工业大模型工程化部署实战!4 卡 L40S 高可用集群(动态资源调度 + 监控告警 + 国产化适配)
人工智能·算法·面试·职场和发展·vllm
D_FW1 小时前
数据结构第六章:图
数据结构·算法
a程序小傲2 小时前
京东Java面试被问:动态规划的状态压缩和优化技巧
java·开发语言·mysql·算法·adb·postgresql·深度优先
HellowAmy2 小时前
我的C++规范 - 玩一个小游戏
开发语言·c++·代码规范
自学不成才2 小时前
深度复盘:一次flutter应用基于内存取证的黑盒加密破解实录并完善算法推理助手
c++·python·算法·数据挖掘
June`3 小时前
全排列与子集算法精解
算法·leetcode·深度优先
徐先生 @_@|||3 小时前
Palantir Foundry 五层架构模型详解
开发语言·python·深度学习·算法·机器学习·架构