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.

这是那个著名的生命游戏,这里的实现是遍历所有的格子,遍历它周围的格子,决定它本身该变成什么样子。
这里要求在原位做修改,但是由于后面的格子要用到前面格子原来的状态,所以相当于要同时保存每个格子现在的状态和下一状态。
当格子由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)
}
}
};
···

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 题目 According to the Wikipedia's article: "The Game of Lif...
    yxwithu阅读 167评论 0 0
  • According to the Wikipedia's article: "The Game of Life, ...
    Jeanz阅读 200评论 0 0
  • 289-Game of Life**QuestionEditorial Solution My Submissio...
    番茄晓蛋阅读 400评论 0 0
  • 走进阳光照耀的清晨,一句早安,一张晨曦,一朵花,一滴水珠,是你对早晨的姿态。 早安! 早晨也给你一个美好的姿态,照...
    梅园遗珠阅读 502评论 0 1