題目
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?
分析
題目很長,就是給你個二維數(shù)組,初始值都是0或1表示狀態(tài),狀態(tài)會隨著周圍的8個數(shù)的和不同而變化,讓你在原數(shù)組上進行狀態(tài)改變,改變的時候要注意每個點都應該是同時改變的,如果先改變一個再改變下一個會導致信息改變。
改變規(guī)則:
現(xiàn)狀態(tài) 鄰居和 狀態(tài)變化
1 <2 1->0
1 [2,3] 1->1
1 >3 1->0
0 =3 0->1
主要難點在原地上改變,又不能逐一判斷改變。
這題使用狀態(tài)記錄法(自己起的名)。原來的狀態(tài)可以是0,1,改成兩位計數(shù),第一位為下一個狀態(tài),第二位為現(xiàn)在的狀態(tài),就得到四個狀態(tài)
00 01 10 11
得到現(xiàn)在狀態(tài)的值 &1
得到下一個狀態(tài)的值 >>1
因為默認下一個狀態(tài)為0,所以只需要考慮下一個狀態(tài)是1的情況
代碼
public void gameOfLife(int[][] board) {
int row = board.length;
if(row == 0) return ;
int col = board[0].length;
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
int sum = getNeighborSum(board, row, col, i, j);
if(board[i][j] == 1 && sum >= 2 && sum <= 3){
board[i][j] = 3;
}else if(board[i][j] == 0 && sum == 3){
board[i][j] = 2;
}
}
}
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
board[i][j] = board[i][j] >> 1;
}
}
}
//有界則取臨界值
public int getNeighborSum(int[][] board, int row, int col, int m, int n){
int sum = 0;
for(int x = Math.max(0, m -1); x <= Math.min(row-1, m+1); ++x){
for(int y = Math.max(0, n-1); y <= Math.min(col-1, n+1); ++y){
sum += board[x][y] & 1;
}
}
return sum - board[m][n];
}