[leetcode 289] Game of Life

Quesiton:

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?

Credits:

分析:

这是非常有名的细胞自动机问题,把m*n矩阵的每个元素看做是细胞,细胞是活的置之为1,是死的置之为0,每个细胞的状态与其周围的8的细胞状态有关。

规则如下:

1、如果一个活的细胞周围的八个细胞中活细胞的数量小于2,则这个细胞置为死细胞状态:

2、如果一个活细胞周围的八个细胞中活细胞数量等于2或是3,则这个细胞置为活细胞状态;

3、如果一个活细胞周围的八个细胞中活细胞数量大于3,则这个细胞置为死细胞状态;

4、如果一个死细胞周围的八个细胞中活细胞数量等于3,则这个细胞置为活细胞状态;


由此规则可以知道,一共有四种转换状态:

状态0:由死细胞转换为死细胞;

状态1:由活细胞转换为活细胞;

状态2:由活细胞转换为死细胞;

状态3:由死细胞转换为活细胞;


如果将状态编号取余,则可以知道余数为0 的细胞最终为死细胞,余数为1的细胞最终状态为活细胞;

所以遍历所求细胞状态周围的八个细胞:统计如果邻居细胞状态为1或2则计数count加1,如果count《2或是count》3,且当前细胞状态为活,则将当前细胞状态值改为2;

如果count == 3,且当前细胞为死细胞,则当前细胞状态值改为3;

最后遍历细胞,将细胞对应值对2取余。


代码如下:

<span style="font-size:14px;">class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size();
		if(m == 0){
			return;
		}
		int n = board[0].size();
		int x[] = {-1,-1,-1,0,1,1,1,0};
		int y[] = {-1,0,1,1,1,0,-1,-1};
		for(int i = 0; i < m; ++i){
			for(int j = 0; j < n; ++j){
				int count = 0;
				for(int k = 0; k < 8; ++k){
					int posx = i + x[k];
					int posy = j + y[k];
					if(posx >= 0 && posx < m && posy >= 0 && posy < n && (board[posx][posy] == 1 || board[posx][posy] == 2)){
						++count;
					}
				}
				if(board[i][j] && (count < 2 || count > 3)){
					board[i][j] = 2;
				}
				else
					if(board[i][j] == 0 && count == 3){
						board[i][j] = 3;
					}
			}

		}
		for(int i = 0; i < m; ++i){
			for(int j = 0; j < n; ++j){
				board[i][j] %= 2;
			}
		}
    }
};</span>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值