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.
這是那個著名的生命游戲,這里的實現是遍歷所有的格子,遍歷它周圍的格子,決定它本身該變成什么樣子。
這里要求在原位做修改,但是由于后面的格子要用到前面格子原來的狀態,所以相當于要同時保存每個格子現在的狀態和下一狀態。
當格子由0變0時,我們存0;
當格子由1變1時,我們存1;
當格子由0變1時,我們存2;
當格子由1變0時,我們存3;
然后在把所有格子遍歷過以后,再遍歷一遍整個板子,把2和3映射回1和0.
···
var gameOfLife = function(board) {
var row = board.length;
if (row===0)
return;
var col = board[0].length;
for (var i = 0;i < row;i++) {
for (var j = 0;j < col;j++) {
var nb = -board[i][j];
for (var ii = i-1;ii<=i+1;ii++) {
if (ii<0||ii>row-1)
continue;
for (var jj = j-1;jj<=j+1;jj++) {
if (jj<0||jj>col-1)
continue;
var now = board[ii][jj];
if(now===1||now===3)
nb++;
}
}
if (board[i][j]===0) {
if (nb===3)
board[i][j]=2;
} else {
if (nb!==2&&nb!==3)
board[i][j]=3;
}
}
}
for (i = 0;i < row;i++) {
for (j = 0;j < col;j++) {
board[i][j] === 2 ? board[i][j] = 1 : (board[i][j] === 3 ? board[i][j] = 0 : 0)
}
}
};
···