leetcode289 - Game of Life(faster than 100.00% and less than 85.57% )

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

Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population…
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.
个人觉得这道题还算简单,可能唯一的难点在于不适用额外的空间这一点,因此我添加了两种额外的状态 -1 和 2 ,-1表示活->死,2表示死->活
代码如下:

class Solution {
public:
    void isAlive(vector<vector<int>>& board, int i, int j){
        int live_neighbors = 0;
        //等于-1表示上一状态是活的,等于2表示上一状态是死亡的
        if(i > 0 and j > 0 and abs(board[i-1][j-1]) == 1)live_neighbors++;
        if(i > 0 and abs(board[i-1][j]) == 1)live_neighbors++;
        if(i > 0 and j < board[0].size()-1 and abs(board[i - 1][j + 1]) == 1)live_neighbors++;
        if(j < board[0].size()-1 and abs(board[i][j + 1]) == 1)live_neighbors++;
        if(i < board.size()-1 and j < board[0].size()-1 and (board[i + 1][j + 1]) == 1)live_neighbors++;
        if(i < board.size()-1 and abs(board[i + 1][j]) == 1)live_neighbors++;
        if(i < board.size()-1 and j > 0 and abs(board[i + 1][j - 1]) == 1)live_neighbors++;
        if(j > 0 and abs(board[i][j - 1]) == 1)live_neighbors++;
        if(board[i][j] == 0){
            if(live_neighbors == 3)board[i][j] = 2;
        }
        else
        {
            if(live_neighbors < 2 or live_neighbors > 3)board[i][j] = -1;
        }
    }
    void gameOfLife(vector<vector<int>>& board) {
        for(auto i = 0; i< board.size(); i++)
            for(auto j = 0; j< board[0].size(); j++)
                isAlive(board, i, j);
        for(auto i = 0; i< board.size(); i++)
            for(auto j = 0; j< board[0].size(); j++){
                if(board[i][j] > 0)board[i][j] = 1;
                else board[i][j] = 0;
            }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值