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

1089

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



