According to theWikipedia's article: "TheGame of Life, also known simply asLife, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given aboardwithmbyncells, each cell has an initial statelive(1) ordead(0). Each cell interacts with itseight neighbors(horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
Write a function to compute the next state (after one update) of the board given its current state.
Follow up:
Credits:
Special thanks to@jianchao.li.fighterfor adding this problem and creating all test cases.
class Solution {
public void gameOfLife(int[][] board) {
if (board == null || board.length == 0) return;
int n = board.length, m = board[0].length;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
int neiLive = 0;
for (int x = -1; x <= 1; x++){
for (int y = -1; y <= 1; y++){
int xx = i + x;
int yy = j + y;
if (xx < 0 || xx >= n || yy < 0 || yy >= m || (xx == i && yy == j)) continue;
if (board[xx][yy] == 1 || board[xx][yy] == 2) neiLive++;
}
}
if (board[i][j] == 1){
if (neiLive <=1 || neiLive > 3) board[i][j] = 2;
}
else{
if (neiLive == 3){
board[i][j] = 3;
}
}
}
}
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
board[i][j] = board[i][j] % 2;
}
}
}
}