个人练习-Leetcode-289. Game of Life

题目链接:https://leetcode.cn/problems/game-of-life/

题目大意:AC元胞自动机,矩阵内每个元素的下一个时刻的值根据周围8个元素的值改变。详细规则略。

思路:模拟即可。感觉应该算简单题而不是中等…

完整代码

class Solution {
public:
    int checkLive(vector<vector<int>>& board, int row, int col) {
        int m = board.size(), n = board[0].size();
        int live = 0;
        for (int i = row-1; i <= row+1; i++) {
            for (int j = col-1; j <= col+1; j++) {
                if (i < m && i >= 0 && j < n && j >= 0) {
                    if (!(i == row && j == col)) {
                        live += board[i][j];
                    }
                }
            }
        }
        return live;
    }

    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size(), n = board[0].size();
        vector<vector<int>> next(m, vector<int> (n));
        for (int row = 0; row < m; row++) {
            for (int col = 0; col < n; col++) {
                int live = checkLive(board, row, col);
                if (board[row][col]) {
                    if (live == 2 || live == 3)
                        next[row][col] = 1;
                    else
                        next[row][col] = 0;
                }
                else {
                    if (live == 3)
                        next[row][col] = 1;
                }
            }
        }

        board = next;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)