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

运行结果


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

相关推荐
一叶落4385 分钟前
LeetCode 151. 反转字符串中的单词(C语言)【双指针 + 字符串处理】
c语言·数据结构·算法·leetcode
wangjialelele6 分钟前
详解Redis终端操作和Redis-plus-plus接口使用
linux·数据库·c++·redis·分布式·缓存·中间件
_olone6 分钟前
牛客每日一题:刷题统计(Java)
java·算法·容斥原理·牛客
无敌憨憨大王7 分钟前
DFS(深搜)
算法·深度优先·图论
junnhwan7 分钟前
LeetCode Hot 100——栈
java·数据结构·算法·leetcode·hot 100
hyl200129 分钟前
c++ SCIP求解整数规划模型
开发语言·c++
sqyno1sky10 分钟前
代码动态生成技术
开发语言·c++·算法
圣保罗的大教堂10 分钟前
leetcode 1727. 重新排列后的最大子矩阵 中等
leetcode
superior tigre11 分钟前
347 前k个高频元素
数据结构·算法·leetcode
2401_8535765015 分钟前
C++中的策略模式变体
开发语言·c++·算法