1. 非原地的解答,通过四周补0可以很自然的按照规则写出下一代的状态
Game of Life
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
- Any live cell with fewer than two live neighbors dies, as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population..
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state.
Follow up:
- Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
- In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
if (board.size() == 0 || board[0].size() == 0) return;
size_t m = board.size();
size_t n = board[0].size();
vector<vector<int> > b;
vector<int> first(n+2,0);
b.push_back(first);
for (size_t ii = 0; ii < m; ++ii) {
vector<int> r(n+2,0);
for (size_t jj = 0; jj < n; ++jj) {
r[jj+1] = board[ii][jj];
}
b.push_back(r);
}
vector<int> last(n+2,0);
b.push_back(last);
for (size_t i = 1; i < m+1; ++i) {
for (size_t j = 1; j < n+1; ++j) {
int nei = b[i-1][j-1]+b[i-1][j]+b[i-1][j+1]+b[i][j-1]+b[i][j+1]+b[i+1][j-1]+b[i+1][j]+b[i+1][j+1];
if (nei < 2) {
board[i-1][j-1] = 0;
} else if ((nei == 2 || nei == 3) && board[i-1][j-1] == 1) {
board[i-1][j-1] = 1;
} else if (nei == 3 && board[i-1][j-1] == 0) {
board[i-1][j-1] = 1;
} else if (nei > 3 && board[i-1][j-1] == 1) {
board[i-1][j-1] = 0;
}
}
}
}
};
本文介绍了一个基于生命游戏规则的算法实现。该算法遵循英国数学家约翰·康威于1970年提出的细胞自动机原理,通过计算每个细胞周围八个邻居的状态来决定其生死状态的变化。文中提供了一种非原地的解决方案,通过对边界进行特殊处理,能够有效地计算出细胞的下一代状态。
7万+

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



