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?
Credits:
这几天节奏感觉慢下来了,但是不要紧,该干嘛还是干嘛。
填一下之前挖的坑。这道题就是一道,当时用了空间O(mn)做的。今天补充一个O(1)的解法。
思路是参考网上的,但是很容易明白。对于要inplace更新,需要对更新的状态有特殊的定义,能够保证既能够找到原始的数据,又能够同时可以更新。
于是有了以下的更新状态图:
dead --> dead == 0 --> 0 binary: 00
live --> live = 1 --> 1 binary: 01
live --> dead = 1 --> 2 binary: 10
dead -- > live = 0 --> 3 binary: 11
在统计细胞周围的live细胞的时候,board[x][y] == 1 或者2 都是满足条件的。这样定义状态的好处是在使用一个遍历通过取模的方式就可以得到最后的结果了。3%2 = 1; 2%2 = 0 取模的结果跟这个细胞的更新的结果是一致的。
代码:
public void gameOfLife(int[][] board) {
if(board == null || board.length == 0 || board[0].length == 0) return;
int row = board.length;
int col = board[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
int count = getLive(board, i, j);
if(board[i][j] == 0 && count == 3){
board[i][j] = 3;// dead --> live
}else if(board[i][j] == 1 && (count<2 || count>3)){
board[i][j] = 2;//live --> dead
}
}
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
board[i][j] = board[i][j]%2;
}
}
}
private int getLive(int [][] board, int i, int j){
int count = 0;
for(int x = i-1;x<=i+1;x++){
for(int y=j-1;y<=j+1;y++){
if(x<0 || x>=board.length || y<0 || y>=board[0].length || (x == i && y == j)) continue;
if(board[x][y] == 1 || board[x][y] == 2){
count++;
}
}
}
return count;
}