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

运行结果


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

相关推荐
柳鲲鹏几秒前
RGB转换为NV12,查表式算法
linux·c语言·算法
橘颂TA几秒前
【剑斩OFFER】算法的暴力美学——串联所有单词的字串
数据结构·算法·c/c++
Kuo-Teng1 分钟前
LeetCode 73: Set Matrix Zeroes
java·算法·leetcode·职场和发展
mit6.8244 分钟前
[HDiffPatch] 补丁算法 | `patch_decompress_with_cache` | `getStreamClip` | RLE游程编码
c++·算法
程序猿20234 分钟前
Python每日一练---第六天:罗马数字转整数
开发语言·python·算法
葵续浅笑23 分钟前
LeetCode - 杨辉三角 / 二叉树的最大深度
java·数据结构·算法·leetcode
杨筱毅40 分钟前
【穿越Effective C++】条款13:以对象管理资源——RAII原则的基石
开发语言·c++·effective c++
qq_4798754341 分钟前
RVO和移动语义
前端·算法
菜小麒41 分钟前
推荐算法的八股文
算法·机器学习·推荐算法
煤球王子1 小时前
学而时习之:C++中的引用
c++