Game of Life 解答

Question

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):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. 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:

  1. 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.
  2. 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?

Solution

这题的关键在于合适的编码。我们用两位来代表每个cell的状态。

after  prev

1    0  以前是dead,经过一次update后为live

1    1  以前是live,经过一次update后为live

0    1  以前是live,经过一次update后为dead

0    0  以前是dead,经过一次update后为dead

由此我们看到取得prev位可以用%操作,取得after位可以用/操作。

因此我们遍历两遍2维数组。第一遍是将所有元素编码成上述两位形式。第二遍是除法操作,得到after。

Time complexity O(mn), space cost O(1)

 public class Solution {
public void gameOfLife(int[][] board) {
int[][] directions = {{-1,0},{1,0},{0,1},{0,-1},{-1,-1},{-1,1},{1,-1},{1,1}};
int m = board.length, n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int prev = board[i][j];
int liveCount = 0, deadCount = 0;
for (int k = 0; k < 8; k++) {
int newX = i + directions[k][0];
int newY = j + directions[k][1];
if (newX < 0 || newX >= m || newY < 0 || newY >= n) {
continue;
}
if (board[newX][newY] % 2 == 1) {
liveCount++;
}
}
if (prev == 0) {
if (liveCount == 3) {
board[i][j] += 2;
}
} else {
if (liveCount == 2 || liveCount == 3) {
board[i][j] += 2;
}
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = board[i][j] / 2;
}
}
}
}
上一篇:AlertDialog.Builder对话框类的用法


下一篇:【Python】 docker-py 用Python调用Docker接口