LeetCode Game of Life

LeetCode 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):

  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.

Write a function to compute the next state (after one update) of the board given its current state.

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. 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 the border of the array. How would you address these problems?

本题有关康威生命游戏,第一次听说。。。

给一个二维矩阵,0表示死亡,1表示活着。每个细胞根据周围8个细胞的状态,有如下跳转规则:

  1. 活着的细胞周围有少于2个活着的细胞,则该细胞死亡
  2. 活着的细胞周围有2个或3个活着的细胞,则该细胞继续活着
  3. 活着的细胞周围有多于3个活着的细胞,则该细胞死亡
  4. 死亡的细胞周围有3个活着的细胞,则该细胞复活

最简单的方法是复制一个矩阵,遍历原矩阵然后更新新矩阵。但本题的难点是,要在in-place的情况下更新原矩阵。如果还是像之前那样更新的话,当前细胞的状态更新之后,会影响到后续细胞的判断,不可行。

参考网上题解,使用编码方法。

因为输入是以int来存储细胞状态的,int可以存储的状态数就很多了,不仅仅局限于0和1。

假设细胞状态重新编码如下:

  • 0:0→0,原来死亡,现在还死亡
  • 1:1→1,原来活着,现在还活着
  • 2:1→0,原来活着,现在死亡
  • 3:0→1,原来死亡,现在活着

则还是像之前一样,遍历细胞的周围8个点,根据以上编码可以知道周围细胞更新前的状态,比如某个邻居的状态是2,则知道该邻居更新前是1活着的。

所有细胞都更新完之后,需要复原成0,1编码,则状态为0和2表示新状态是死亡0,状态是1和3表示新状态是活着1。这可以用新状态对2取余数得到。

代码如下:

class Solution {
public:
	void gameOfLife(vector<vector<int>>& board) {
		int m = board.size(), n = 0;
		if (m != 0)n = board[0].size();
		if (m == 0 || n == 0)return;
		vector<vector<int>> dirs = { {-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1} };
		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				int lives = 0;
				for (int k = 0; k < dirs.size(); ++k) {
					int x = i + dirs[k][0], y = j + dirs[k][1];
					if (x >= 0 && x < m&&y >= 0 && y < n && (board[x][y] == 1 || board[x][y] == 2))++lives;
				}
				if (board[i][j] == 1 || board[i][j] == 2) {
					if (lives < 2 || lives > 3)board[i][j] = 2;
					else board[i][j] = 1;
				}
				else if (lives == 3)board[i][j] = 3;
			}
		}
		for (int i = 0; i < m; ++i) {
			for (int j = 0; j < n; ++j) {
				board[i][j] %= 2;
			}
		}
	}
};

本代码提交AC,用时3MS。

Leave a Reply

Your email address will not be published. Required fields are marked *