No.247 - LeetCode[289] Game of Life - 状压矩阵状态机

该博客主要介绍了如何使用C++实现康威的生命游戏,这是一个经典的细胞自动机模型。通过遍历二维数组表示的网格,计算每个细胞的生存状态,模拟细胞的演化过程。算法涉及到了邻域判断和位运算,对于理解动态系统和编程技巧有一定帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很显然int对于存0,1来说空间很富裕

/*
 * @lc app=leetcode id=289 lang=cpp
 *
 * [289] Game of Life
 */

// @lc code=start
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int N = board.size();
        if(N <= 0) return ;
        int M = board[0].size();
        vector<int> dirx = {-1,-1,-1,0,1,1,1,0};
        vector<int> diry = {-1,0,1,1,1,0,-1,-1};
        int cnt = 0;
        int xx,yy;
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                cnt = 0;
                for(int k=0;k<8;k++){
                    xx = i+dirx[k];
                    yy = j+diry[k];
                    if(0 <= xx && xx < N && 0 <= yy && yy < M && (board[xx][yy]&1) ) cnt++;
                }
                board[i][j] += (board[i][j] << 1);
                if( (board[i][j]&1) && cnt < 2) board[i][j] >>= 1;
                if( (board[i][j]&1) && cnt > 3) board[i][j] >>= 1;
                if( !(board[i][j]&1) && cnt == 3) board[i][j] += 2;
            }
        }
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
                board[i][j] >>= 1;
            }
        }
    }
};
// @lc code=end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值