LeetCode 289.生命游戏

题目

点击查看原题

思路
遍历每一个网格点,同时额外写一个辅助函数查看这个网格点周围有几个活细胞;
分情况讨论就OK了
代码
class Solution {
public:
    int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
    int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
    int findCnt(int x, int y, vector<vector<int>>& board1){
        int row = board1.size(), col = board1[0].size(), ans = 0;
        for(int k = 0; k < 8; k ++){
            int x0 = x + dx[k], y0 = y + dy[k];
            //对于这种会越界的问题,先判断下标是不是合法的,不合法直接continue,这种方法用起来好爽,哈哈哈
            if(x0 < 0 || x0 >= row || y0 < 0 || y0 >= col) continue;
            if(board1[x0][y0] == 1) ans++;
        }
        return ans;
    }
    void gameOfLife(vector<vector<int>>& board) {
        vector<vector<int>> ans = board;
        for(int i = 0; i < board.size(); i ++){
            for(int j = 0; j < board[0].size(); j ++){
            //findCnt()函数用来找到周围有多少个活细胞
                int temp = findCnt(i, j, board);
                //在写这种多种条件判断的情况时,只写出来那种你需要对它进行操作的情况,不进行任何操作的情况就不要去判断了
                if(board[i][j] == 0 && temp == 3) ans[i][j] = 1;
                else if(board[i][j] == 1 && (temp < 2) || temp > 3) ans[i][j] = 0;
            }
        }
        board = ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值