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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [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]
]

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?

属于一道技巧性比较强的题。

首先,如果使用额外的m*n空间的话,就没什么好做的了。这里要求的是不使用额外空间。

解法如下:

首先,我们将1(live)或者0(dead)这样理解:

1就是 01 代表next state = 0, current_state = 1

0就是 00 代表next state = 0, current_state = 0

那么也就是说,board[i][j]同时记录着current state和next state。而且next state默认为0(dead)

那么为了满足4条规则,我们需要处理以下两种情况:

(1) current state = 1且live neighbors个数为2或者3

          这种情况下,next state 为 1(live)。因此board[i][j]要由 01 变为 11, 即从1变为3

(1) current state = 0且live neighbors个数为3

          这种情况下,next state 为 1(live)。因此board[i][j]要由 00 变为 10, 即从0变为2

那么在改变next state的时候,并没有改变current state的过程。因此就不再需要额外的空间了

代码如下:

class Solution {
    public void gameOfLife(int[][] board) {
        //borad[i][j] = 0代表 00 即next:dead  present:dead
        //borad[i][j] = 1代表 01 即next:dead  present:live
        int m = board.length;
        int n = board[0].length;
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                int live_neighs = get_live_neigh(board,i,j);//board的改变不影响get_live_neigh函数的正确性
                int current_state = board[i][j]&1;
                if(current_state==1){
                    if(live_neighs==2 || live_neighs==3){
                        board[i][j] = 3;// 11
                    }
                }
                else if(current_state==0){
                    if(live_neighs==3){
                        board[i][j] = 2;//10
                    }
                }
            }
        }
        
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                int next_state = board[i][j]>>1;
                board[i][j] = next_state;
            }
        }
    }
    
    private int get_live_neigh(int[][] board,int i,int j){
        int res = 0;
        for(int m = -1;m<=1;m++){
            for(int n  = -1;n<=1;n++){
                if(!(m==0&&n==0) && i+m>=0 && i+m<board.length && j+n>=0 && j+n<board[0].length){
                    int neigh_current_state = board[i+m][j+n]&1;
                    res += neigh_current_state;
                }
            }
        }
        return res;
    }
    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Game of LifeC++代码示例: ```cpp #include <iostream> #include <vector> #include <chrono> #include <thread> #include <cstdlib> using namespace std; class GameOfLife { private: vector<vector<int>> grid; int rows, columns; public: GameOfLife(int r, int c) : rows(r), columns(c) { grid.resize(rows, vector<int>(columns, 0)); } void initialize() { srand(time(NULL)); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { grid[i][j] = rand() % 2; } } } int getNeighbourCount(int row, int col) { int count = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { int r = row + i; int c = col + j; if (r >= 0 && r < rows && c >= 0 && c < columns && !(i == 0 && j == 0)) { count += grid[r][c]; } } } return count; } void nextGeneration() { vector<vector<int>> newGrid(rows, vector<int>(columns, 0)); for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { int neighbourCount = getNeighbourCount(i, j); if (grid[i][j] == 0 && neighbourCount == 3) { newGrid[i][j] = 1; } else if (grid[i][j] == 1 && (neighbourCount == 2 || neighbourCount == 3)) { newGrid[i][j] = 1; } else { newGrid[i][j] = 0; } } } grid = newGrid; } void print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (grid[i][j] == 1) { cout << "* "; } else { cout << ". "; } } cout << endl; } } }; int main() { int rows = 40, columns = 40; GameOfLife gol(rows, columns); gol.initialize(); while (true) { gol.print(); gol.nextGeneration(); this_thread::sleep_for(chrono::milliseconds(100)); system("clear"); } return 0; } ``` 此代码实现了一个Game of Life模拟器,它使用随机值初始化单元格,并在每次迭代中计算每个单元格周围的邻居数量,然后使用规则进行更新。最后,它在控制台中打印游戏板并在每次迭代后清除屏幕。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值