地址:https://leetcode-cn.com/problems/game-of-life/
方法一:先把需要修改的存成另外的数值,然后再修改回来。
Java 代码:
public class Solotion {
// 至少要遍历两次
// 非原地修改
// 原地修改
// die(0) -> live (-1)
// live(1) -> die (2)
// count 表示有几个活着的细胞,值为 1 和 2 都是活着
// update -1 -> 1, 2 -> 0
public void gameOfLife(int[][] board) {
int rows = board.length;
if (rows == 0) {
return;
}
int cols = board[0].length;
if (cols == 0) {
return;
}
// 上下左右加四个对角线
int[][] directions = new int[][]{{0, -1}, {0, 1}, {1, 0}, {-1, 0}, {1, 1}, {-1, 1}, {1, -1}, {-1, -1}};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 0) {
int lives = count(board, i, j, rows, cols, directions);
if (lives == 3) {
board[i][j] = -1;
}
}
if (board[i][j] == 1) {
int lives = count(board, i, j, rows, cols, directions);
if (lives < 2 || lives > 3) {
board[i][j] = 2;
}
}
}
}
update(board, rows, cols);
}
private void update(int[][] board, int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == -1) {
board[i][j] = 1;
} else if (board[i][j] == 2) {
board[i][j] = 0;
}
}
}
}
private boolean inArea(int i, int j, int rows, int cols) {
return i >= 0 && i < rows && j >= 0 && j < cols;
}
private int count(int[][] board, int i, int j, int rows, int cols, int[][] directions) {
int res = 0;
for (int[] direction : directions) {
int newX = i + direction[0];
int newY = j + direction[1];
if (inArea(newX, newY, rows, cols) && (board[newX][newY] == 1 || board[newX][newY] == 2)) {
res++;
}
}
return res;
}
}
方法二:使用整数的高位存储修改以后的信息,这样不会覆盖。
Java 代码:
public class Solotion {
// 至少要遍历两次,使用位运算进行原地修改
public void gameOfLife(int[][] board) {
int rows = board.length;
if (rows == 0) {
return;
}
int cols = board[0].length;
if (cols == 0) {
return;
}
// 上下左右加四个对角线
int[][] directions = new int[][]{{0, -1}, {0, 1}, {1, 0}, {-1, 0}, {1, 1}, {-1, 1}, {1, -1}, {-1, -1}};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// 数 8 个方向存活的生命个数
int cnt = 0;
for (int[] direction : directions) {
int newX = i + direction[0];
int newY = j + direction[1];
if (inArea(newX, newY, rows, cols)) {
// 只累加最低位
cnt += board[newX][newY] & 1;
}
}
if (board[i][j] == 1) {
if (cnt == 2 || cnt == 3) {
board[i][j] |= 2;
}
} else {
if (cnt == 3) {
board[i][j] |= 2;
}
}
}
}
// 恢复
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// 右移一位,用高位 bit 覆盖地位 bit
board[i][j] >>= 1;
}
}
}
private boolean inArea(int i, int j, int rows, int cols) {
return i >= 0 && i < rows && j >= 0 && j < cols;
}
}