289. Game of Life

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.

這是那個著名的生命游戲,這里的實現(xiàn)是遍歷所有的格子,遍歷它周圍的格子,決定它本身該變成什么樣子。
這里要求在原位做修改,但是由于后面的格子要用到前面格子原來的狀態(tài),所以相當于要同時保存每個格子現(xiàn)在的狀態(tài)和下一狀態(tài)。
當格子由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)
}
}
};
···

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,779評論 0 33
  • 題目 According to the Wikipedia's article: "The Game of Lif...
    yxwithu閱讀 166評論 0 0
  • According to the Wikipedia's article: "The Game of Life, ...
    Jeanz閱讀 198評論 0 0
  • 289-Game of Life**QuestionEditorial Solution My Submissio...
    番茄曉蛋閱讀 400評論 0 0
  • 走進陽光照耀的清晨,一句早安,一張晨曦,一朵花,一滴水珠,是你對早晨的姿態(tài)。 早安! 早晨也給你一個美好的姿態(tài),照...
    梅園遺珠閱讀 500評論 0 1