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)
}
}
};
···
网友评论