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

被折叠的 条评论
为什么被折叠?



