leetcode289. 生命游戏

注意,更新要基于原状态更新,不是基于新状态的部分更新
法一:额外数组。对于边界,全部视为0。第一次通过的代码。
class Solution {
public void gameOfLife(int[][] board) {
int m = board.length,n = board[0].length;
int[][] temp = new int[m+2][n+2];
for(int i = 0;i < m;++i){
for(int j = 0;j < n;++j){
temp[i+1][j+1] = board[i][j];
}
}
for(int i = 1;i < m + 1;++i){
for(int j = 1;j < n + 1;++j){
int count = temp[i-1][j-1] + temp[i-1][j] + temp[i-1][j+1] + temp[i][j-1] + temp[i][j+1] + temp[i+1][j-1] + temp[i+1][j] + temp[i+1][j+1];
if(board[i-1][j-1] == 1 && (count > 3 || count < 2)) board[i-1][j-1] = 0;
else if(board[i-1][j-1] == 0 && count == 3) board[i-1][j-1] = 1;
}
}
}
}
法二:原地修改。制定新规则,由活变死赋值-1,由死变活赋值2。最后遍历一遍,更新所有修改了的值。
class Solution {
public void gameOfLife(int[][] board) {
int[] neighbors = {0, 1, -1};
int m = board.length;
int n = board[0].length;
// 遍历面板每一个格子里的细胞
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
// 对于每一个细胞统计其八个相邻位置里的活细胞数量
int liveNeighbors = 0;
for (int x = 0; x < 3; ++x) {
for (int y = 0; y < 3; ++y) {
if(neighbors[x] == 0 && neighbors[y] == 0) continue;
// 相邻位置的坐标
int r = i + neighbors[x];
int c = j + neighbors[y];
// 查看相邻的细胞是否是活细胞
if ((r < m && r >= 0) && (c < n && c >= 0) && (Math.abs(board[r][c]) == 1)) {
liveNeighbors += 1;
}
}
}
if ((board[i][j] == 1) && (liveNeighbors < 2 || liveNeighbors > 3)) {
board[i][j] = -1;// -1 代表这个细胞过去是活的现在死了
}else if (board[i][j] == 0 && liveNeighbors == 3) {
board[i][j] = 2;// 2 代表这个细胞过去是死的现在活了
}
}
}
// 遍历 board 得到一次更新后的状态
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (board[row][col] > 0) board[row][col] = 1;
else board[row][col] = 0;
}
}
}
}
浙公网安备 33010602011771号