个人练习-Leetcode-289. Game of Life

本文解析了LeetCode上生命游戏问题的实现方法,采用C++语言模拟实现了一个二维矩阵的细胞自动机,根据周围细胞的状态更新当前细胞状态。文章通过具体代码展示了如何计算每个细胞周围的活细胞数量,并据此确定其下一状态。

题目链接:https://leetcode.cn/problems/game-of-life/

题目大意:AC元胞自动机,矩阵内每个元素的下一个时刻的值根据周围8个元素的值改变。详细规则略。

思路:模拟即可。感觉应该算简单题而不是中等…

完整代码

class Solution {
public:
    int checkLive(vector<vector<int>>& board, int row, int col) {
        int m = board.size(), n = board[0].size();
        int live = 0;
        for (int i = row-1; i <= row+1; i++) {
            for (int j = col-1; j <= col+1; j++) {
                if (i < m && i >= 0 && j < n && j >= 0) {
                    if (!(i == row && j == col)) {
                        live += board[i][j];
                    }
                }
            }
        }
        return live;
    }

    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size(), n = board[0].size();
        vector<vector<int>> next(m, vector<int> (n));
        for (int row = 0; row < m; row++) {
            for (int col = 0; col < n; col++) {
                int live = checkLive(board, row, col);
                if (board[row][col]) {
                    if (live == 2 || live == 3)
                        next[row][col] = 1;
                    else
                        next[row][col] = 0;
                }
                else {
                    if (live == 3)
                        next[row][col] = 1;
                }
            }
        }

        board = next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值