題目
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?
分析
題目很長(zhǎng),就是給你個(gè)二維數(shù)組,初始值都是0或1表示狀態(tài)响禽,狀態(tài)會(huì)隨著周圍的8個(gè)數(shù)的和不同而變化录粱,讓你在原數(shù)組上進(jìn)行狀態(tài)改變悟民,改變的時(shí)候要注意每個(gè)點(diǎn)都應(yīng)該是同時(shí)改變的米母,如果先改變一個(gè)再改變下一個(gè)會(huì)導(dǎo)致信息改變斩祭。
改變規(guī)則:
現(xiàn)狀態(tài) 鄰居和 狀態(tài)變化
1 <2 1->0
1 [2,3] 1->1
1 >3 1->0
0 =3 0->1
主要難點(diǎn)在原地上改變汹碱,又不能逐一判斷改變。
這題使用狀態(tài)記錄法(自己起的名)项玛。原來的狀態(tài)可以是0,1貌笨,改成兩位計(jì)數(shù),第一位為下一個(gè)狀態(tài)襟沮,第二位為現(xiàn)在的狀態(tài)锥惋,就得到四個(gè)狀態(tài)
00 01 10 11
得到現(xiàn)在狀態(tài)的值 &1
得到下一個(gè)狀態(tài)的值 >>1
因?yàn)槟J(rèn)下一個(gè)狀態(tài)為0,所以只需要考慮下一個(gè)狀態(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];
}