LeetCode 289. 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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

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?

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input: 
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]

Solution

Actually, we need to solve it in constant space, so we have to mark our position properly. If live node becomes die node, we give them -1, or die node becomes live node, we give them 2. And when we go through the board, we can just count the node which abs value equals to 1. At the end, we can convert 2 to 1, otherwise, it stays 0.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// time:O(m * n) space:O(1)
public void gameOfLife2(int[][] board) {
if (board == null || board.length == 0) return;

int[] neighbors = {0, -1, 1}; // 8 neighbors we have to check.

int m = board.length;
int n = board[0].length;

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {

int numOfLive = 0;

for (int a = 0; a < 3; a++) {
for (int b = 0; b < 3; b++) {
if (!(neighbors[a] == 0 && neighbors[b] == 0)) {
int r = i + neighbors[a];
int c = j + neighbors[b];

if ((r < m && r >= 0) && (c < n && c >= 0) && Math.abs(board[r][c]) == 1) {
numOfLive++;
}
}
}
}
// rule 1 or 3
if ((board[i][j] == 1) && (numOfLive < 2 || numOfLive > 3)) {
board[i][j] = -1;
}
if (numOfLive == 3 && board[i][j] == 0) {
board[i][j] = 2;
}
}
}

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] > 0) {
board[i][j] = 1;
} else {
board[i][j] = 0;
}
}
}
}

Reference