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

运行结果


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

相关推荐
我要升天!2 分钟前
QT -- QSS界面优化
开发语言·c++·qt
JANGHIGH4 分钟前
c++ 多线程(四)
开发语言·c++
flashlight_hi8 分钟前
LeetCode 分类刷题:987. 二叉树的垂序遍历
数据结构·算法·leetcode
小尧嵌入式8 分钟前
C++模板
开发语言·c++·算法
锦瑟弦音8 分钟前
Luban + Cocos3.8.7 + Typescript + Json
笔记·游戏·typescript
仰泳的熊猫13 分钟前
1120 Friend Numbers
数据结构·c++·算法·pat考试
BestOrNothing_201514 分钟前
C++ 成员函数运算符重载深度解析
c++·八股·运算符重载·operator·this指针·const成员函数·const引用
ALex_zry14 分钟前
C++中经典的定时器库与实现方式
开发语言·c++
槿花Hibiscus17 分钟前
C++基础:session实现和http server类最终组装
服务器·c++·http·muduo
仰泳的熊猫18 分钟前
1116 Come on! Let‘s C
数据结构·c++·算法·pat考试