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.
這是那個(gè)著名的生命游戲,這里的實(shí)現(xiàn)是遍歷所有的格子鹃操,遍歷它周圍的格子耘拇,決定它本身該變成什么樣子瞧哟。
這里要求在原位做修改玩裙,但是由于后面的格子要用到前面格子原來(lái)的狀態(tài)姊舵,所以相當(dāng)于要同時(shí)保存每個(gè)格子現(xiàn)在的狀態(tài)和下一狀態(tài)盐类。
當(dāng)格子由0變0時(shí)寞奸,我們存0;
當(dāng)格子由1變1時(shí)在跳,我們存1枪萄;
當(dāng)格子由0變1時(shí),我們存2硬毕;
當(dāng)格子由1變0時(shí)呻引,我們存3;
然后在把所有格子遍歷過(guò)以后吐咳,再遍歷一遍整個(gè)板子逻悠,把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)
}
}
};
···