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

  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?

题目链接:

思路分析

Game of life,给一m×n的board,每一个位置代表一个cell,有起始状态活着1和死了0,可以与周围的8个邻居进行互动。board的下一个状态由下面的条件确定:

  1. 活着的cell,如果有少于两个活着的邻居,下一个状态会死。人口太少。
  2. 活着的cell,如果有两个或三个活着的邻居,下一个状态会继续活着。正常状态。
  3. 活着的cell,如果有多于三个活着的邻居,下一个状态会死亡。人口过多。
  4. 死了的cell,如果有正好三个活着的邻居,下一个状态会复活。人口繁衍。

计算board的下一个状态。

follow up:

  1. in-place实现。
  2. 正常状态下board应该是无限的,如何处理二维数组的边界。

我们拓展一下,用两个bits存储每一个cell的变化

[2nd bit, 1st bit] = [next state, current state]

  • 00 dead (next) <- dead (current)
  • 01 dead (next) <- live (current)
  • 10 live (next) <- dead (current)
  • 11 live (next) <- live (current)

一开始所有的cell都是00或者01状态,也就是0和1。如果cell能够活下去,就将它变成1*的形式,那么就是0和3个活着的邻居和1和2或3个活着的邻居的情况。我们在第一遍循环的时候只需要对这两种情况进行处理。

然后第二次循环将所有的值右移一位,就是最终结果了,那些活不了的终究活不了。精髓在于:在cell中存储下一个state的状态而不改变原来的state,需要想象,变化是一瞬间同时发生的。

然后是对活着的邻居的统计,对于边界情况,循环时进行判断,不要出现越界的情况。然后是很重要的如何利用一斤改变了的数据,很简单,使用board[i][j] & 1即可判断这个cell现在的状态是死是活。

代码

java

class Solution {
    public void gameOfLife(int[][] board) {
        if (board == null || board.length == 0 || board[0].length == 0){
            return;
        }
        int row = board.length - 1;
        int col = board[0].length - 1;
        for (int i = 0; i <= row; i++){
            for (int j = 0; j <= col; j++){
                int lives = countNeighbours(board, row, col, i, j);
                if (board[i][j] == 1 && lives >= 2 && lives <= 3){
                    board[i][j] = 3;
                }
                if (board[i][j] == 0 && lives == 3){
                    board[i][j] = 2;
                }
            }
        }
        for (int i = 0; i <= row; i++){
            for (int j = 0; j <= col; j++){
                board[i][j] >>= 1;
            }
        }
    }
    
    private int countNeighbours (int[][] board, int row, int col, int i , int j){
        int count = 0;
        for (int x = Math.max(0, i - 1); x <= Math.min(row, i + 1); x++){
            for (int y = Math.max(0, j - 1); y <= Math.min(col, j + 1); y++){
                count += board[x][y] & 1;
            }
        }
        count -= board[i][j] & 1;
        return count;
    }
}
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        if (board.size() == 0)
            return;
        int row = board.size() - 1;
        int col = board[0].size() - 1;
        for (int i = 0; i <= row; i++){
            for (int j = 0; j <= col; j++){
                int lives = countNearLives(board, row, col, i, j);
                if (board[i][j] == 1 && lives >= 2 && lives <= 3)
                    board[i][j] = 3;
                if (board[i][j] == 0 && lives == 3)
                    board[i][j] = 2;
            }
        }
        for (int i = 0; i <= row; i++){
            for (int j = 0; j <= col; j++){
                    board[i][j] >>= 1;
            }
        }
    }
    
    int countNearLives(vector<vector<int>>& board, int row, int col, int i, int j){
        int count = 0;
        for (int x = max(i - 1, 0); x <= min(i + 1, row); x++){
            for (int y = max(j - 1, 0); y <= min(j + 1, col); y++){
                count += board[x][y] & 1;
            }
        }
        count -= board[i][j] & 1;
        return count;
    }
};

时间复杂度: O ( m × n ) O(m×n ) O(m×n)
空间复杂度: O ( 1 ) O(1) O(1)


反思

很喜欢的一道题目,但是犯了很多小错误,要提高写代码的准确率。在count的时候忘记应该去掉自cell的情况,导致返回的count会虚高。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值