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.

题目要求在原位操作,空间复杂度为o(1)

思路:

既然要求是原位操作,那么对于状态board[i][j],live->dead,将值1->2,那么当board[I][j]作为其他位置的邻居时,判断是否>=1即可;dead->live,将值0->-1。当所有位置遍历过后,再次遍历所有位置,值为2的位置,说明更新后状态为dead,值改为0;值为-1的位置,说明更新之后状态为live,值改为1.

代码:

class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m=board.size();
        int n=board[0].size();
        if (m==0||n==0)
            return;
        for (int i=0; i<m; i++)
            for (int j=0; j<n; j++)
                fun(board,i,j,m,n);
        for (int i=0; i<m; i++)
            for (int j=0; j<n; j++)
            {
                if (board[i][j]==2)
                    board[i][j]=0;
                if (board[i][j]==-1)
                    board[i][j]=1;
            }
        
    }
    
    void fun(vector<vector<int>>& board, int i,int j, int m, int n)
    {
        int count=0;
        if (i-1>=0&&board[i-1][j]>=1)
            count++;
        if (i+1<m&&board[i+1][j]>=1)
            count++;
        if (j-1>=0&&board[i][j-1]>=1)
            count++;
        if (j+1<n&&board[i][j+1]>=1)
            count++;
        if (i-1>=0&&j-1>=0&&board[i-1][j-1]>=1)
            count++;
        if (i-1>=0&&j+1<n&&board[i-1][j+1]>=1)
            count++;
        if (i+1<m&&j-1>=0&&board[i+1][j-1]>=1)
            count++;
        if (i+1<m&&j+1<n&&board[i+1][j+1]>=1)
            count++;
        if (board[i][j]==1&&(count<2||count>3))
            board[i][j]++;
        if (board[i][j]==0&&count==3)
            board[i][j]--;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值