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;
                }
            }
        }
    }
};

运行结果


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

相关推荐
CoovallyAIHub14 小时前
港大&字节重磅发布DanceGRPO:突破视觉生成RLHF瓶颈,多项任务性能提升超180%!
深度学习·算法·计算机视觉
感哥14 小时前
C++ STL 常用算法
c++
CoovallyAIHub15 小时前
英伟达ViPE重磅发布!解决3D感知难题,SLAM+深度学习完美融合(附带数据集下载地址)
深度学习·算法·计算机视觉
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
聚客AI1 天前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v1 天前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工2 天前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法