程式語言 - LeetCode - C++ - 289. Game of Life



參考資訊:
https://www.cnblogs.com/grandyang/p/4854466.html

題目:


解答:

class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size();
        int n = board[0].size();
        vector<pair<int, int>> dir = {
            { -1, -1 }, { -1, 0 }, { -1, 1 },
            { 0,  -1 }, { 0, 1 },
            { 1, -1 }, { 1, 0 }, { 1, 1 }
        };

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int live = 0;

                for (auto [dx, dy] : dir) {
                    int x = i + dx;
                    int y = j + dy;

                    if (x >= 0 && x < m && y >= 0 && y < n) {
                        if (abs(board[x][y]) == 1) {
                            live += 1;
                        }
                    }
                }

                if (board[i][j] == 1) {
                    if (live < 2 || live > 3) {
                        board[i][j] = -1;
                    }
                }
                else {
                    if (live == 3) {
                        board[i][j] = 2;
                    }
                }
            }
        }

        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (board[i][j] > 0) {
                    board[i][j] = 1;
                }
                else {
                    board[i][j] = 0;
                }
            }
        }
    }
};