cpp in-space solution, easy to understand

  • 0
    int dx[] = {-1,-1,-1,0,0,1,1,1};
    int dy[] = {-1,0,1,-1,1,-1,0,1};
    class Solution {
        void gameOfLife(vector<vector<int>>& board) {
            if(board.empty()||board[0].empty()) return;
            int m = board.size(), n = board[0].size();
            for(int i=0;i<m;i++) for(int j=0;j<n;j++){
                int count = 0;
                for(int k=0;k<8;k++) if(i+dx[k]>=0 && i+dx[k]<m && j+dy[k]>=0 && j+dy[k]<n && board[i+dx[k]][j+dy[k]]%2) count++;
                if((board[i][j]&&count==2)||count==3) board[i][j]+=2;
            for(int i=0;i<m;i++) for(int j=0;j<n;j++) board[i][j]/=2;

    for one cell, if the next generation is live, we add 2 on it. Then the previous state can be extracted by board[i][j]%2.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.