289. Game of Life

289. 生命游戏

Posted by bbkgl on July 3, 2020

我且为君槌碎黄鹤楼

君亦为吾倒却鹦鹉洲

原地哈希2333。

class Solution {
private:
    static int dx[8];
    static int dy[8];

    inline void check_for_alive(vector<vector<int>> &board, int i, int j) {
        int m = board.size(), n = board[0].size();
        int alive_cnt = 0, dead_cnt = 0;
        for (int a = 0; a < 8; a++) {
            int mi = i + dx[a], nj = j + dy[a];
            if (0 <= mi && mi < m && 0 <= nj && nj < n) {
                if (board[mi][nj] & 1)
                    alive_cnt++;
            }
        }
        if (board[i][j]) {
            if (2 <= alive_cnt && alive_cnt <= 3)
                board[i][j] |= 512;
        } else {
            if (alive_cnt == 3)
                board[i][j] |= 512;
        }
    }

public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size();
        int n = board[0].size();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) check_for_alive(board, i, j);
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j] = (board[i][j] >> 9);
            }
        }
    }
};

int Solution::dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};
int Solution::dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};