289. Game of Life(生命游戏)
题目大意
According to 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.”
The board is made up of an m x n
grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 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.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n
grid board, return the next state.
中文释义
根据维基百科的文章:“生命游戏(Life)是由英国数学家约翰·霍顿·康威于1970年设计的一种元胞自动机。”
棋盘由一个 m x n
的细胞网格组成,每个细胞都有一个初始状态:活(用1表示)或死(用0表示)。每个细胞根据以下四条规则(摘自上述维基百科文章)与其八个邻居(水平、垂直、对角线)相互作用:
- 任何活细胞周围活细胞少于两个,则因孤立而死亡。
- 任何活细胞周围有两个或三个活细胞将存活到下一代。
- 任何活细胞周围有超过三个活细胞将死亡,如同人口过多。
- 任何死细胞周围正好有三个活细胞将变为活细胞,如同繁殖。
下一个状态是通过同时对当前状态中的每个细胞应用上述规则来创建的,其中生与死同时发生。给定 m x n
网格板的当前状态,返回下一个状态。
示例
- 示例 1:
- 输入:
board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
- 输出:
[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
- 输入:
- 示例 2:
- 输入:
board = [[1,1],[1,0]]
- 输出:
[[1,1],[1,1]]
- 输入:
限制条件
m == board.length
n == board[i].length
1 <= m, n <= 25
board[i][j]
是 0 或 1。
进阶问题
- 你能在不使用额外的内存空间的情况下解决此问题吗?请记住,棋盘需要同时更新:你不能先更新一些细胞然后使用它们的更新值来更新其他细胞。
- 在这个问题中,我们使用 2D 数组来表示棋盘。从原理上讲,棋盘是无限的,这可能会在活跃区域侵占数组边界时(即,活细胞到达边界)引起问题。你将如何解决这些问题?
解题思路
该算法通过遍历每个细胞,根据其邻居的活动情况来更新细胞的状态。由于状态更新需要同步进行,算法使用额外的状态标记来表示细胞的变化,并在最后统一更新细胞状态。
代码
class Soluti