跳至主要內容

289. Game of Life


289. Game of Lifeopen in new window

🟠   🔖  数组 矩阵 模拟  🔗 LeetCodeopen in new window

题目

According to Wikipedia's articleopen in new window: "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 neighborsopen in new window (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population.
  4. 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.

Example 1:

Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]

Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]

Example 2:

Input: board = [[1,1],[1,0]]

Output: [[1,1],[1,1]]

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 25
  • board[i][j] is 0 or 1.

Follow up:

  • Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
  • In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?

题目大意

生命游戏 ,简称为 生命 ,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。

给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态: 1 即为 活细胞 (live),或 0 即为 死细胞 (dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律:

  1. 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
  2. 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
  3. 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
  4. 如果死细胞周围正好有三个活细胞,则该位置死细胞复活;

下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。给你 m x n 网格面板 board 的当前状态,返回下一个状态。

进阶:

你可以使用原地算法解决本题吗?请注意,面板上所有格子需要同时被更新:你不能先更新某些格子,然后使用它们的更新后的值再更新其他格子。

本题中,我们使用二维数组来表示面板。原则上,面板是无限的,但当活细胞侵占了面板边界时会造成问题。你将如何解决这些问题?

解题思路

  1. 遍历 board 中的细胞。
  • 根据数组的细胞状态计算新一轮的细胞状态,这里会用到能同时代表过去状态和现在状态的复合状态:

    • 规则 1:如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡。这时候,将细胞值改为 -1,代表这个细胞过去是活的现在死了;
    • 规则 2:如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活。这时候不改变细胞的值,仍为 1
    • 规则 3:如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡。这时候,将细胞的值改为 -1,代表这个细胞过去是活的现在死了。可以看到,因为规则 1 和规则 3 下细胞的起始终止状态是一致的,因此它们的复合状态也一致;
    • 规则 4:如果死细胞周围正好有三个活细胞,则该位置死细胞复活。这时候,将细胞的值改为 2,代表这个细胞过去是死的现在活了。
  1. 根据新的规则更新数组。
  • 现在复合状态隐含了过去细胞的状态,所以我们可以在不复制数组的情况下完成原地更新;

  • 对于最终的输出,需要将 board 转成 01 的形式。因此这时候需要再遍历一次数组:

    • 将复合状态为 2 的细胞的值改为 1
    • 将复合状态为 -1 的细胞的值改为 0
  • 时间复杂度:O(mn),其中 mn 分别为 board 的行数和列数。

  • 空间复杂度:O(1),除原数组外只需要常数的空间存放若干变量。

代码

/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var gameOfLife = function (board) {
	const neighbors = [-1, 0, 1],
		rows = board.length,
		cols = board[0].length;

	// 遍历面板每一个格子里的细胞
	for (let i = 0; i < rows; i++) {
		for (let j = 0; j < cols; j++) {
			// 对于每一个细胞统计其八个相邻位置里的活细胞数量
			let liveNeighbors = 0;
			for (let x = 0; x < 3; x++) {
				for (let y = 0; y < 3; y++) {
					if (!(neighbors[x] == 0 && neighbors[y] == 0)) {
						// 相邻位置的坐标
						let r = i + neighbors[x],
							c = j + neighbors[y];

						// 查看相邻的细胞是否是活细胞
						if (
							r < rows &&
							r >= 0 &&
							c < cols &&
							c >= 0 &&
							Math.abs(board[r][c]) == 1
						) {
							liveNeighbors++;
						}
					}
				}
			}

			// 规则 1 或规则 3
			if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
				// -1 代表这个细胞过去是活的现在死了
				board[i][j] = -1;
			}

			// 规则 4
			if (board[i][j] == 0 && liveNeighbors == 3) {
				// 2 代表这个细胞过去是死的现在活了
				board[i][j] = 2;
			}
		}
	}
	// 遍历 board 得到一次更新后的状态
	for (let i = 0; i < rows; i++) {
		for (let j = 0; j < cols; j++) {
			if (board[i][j] > 0) {
				board[i][j] = 1;
			} else {
				board[i][j] = 0;
			}
		}
	}
};

相关题目

相关题目
- [73. 矩阵置零](./0073.md)