c++ solution


  • 0
    Q
    class Solution {
    public:
        void gameOfLife(vector<vector<int>>& board) {
            if(board.empty() || board[0].empty())
                return;
            int len1 = board.size(), len2 = board[0].size();
            vector<pair<int,int>> dir{{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
            int res = 0;
            //vector<vector<int>> t = board;
            vector<vector<int>> v(len1,vector<int>(len2,0));
            
            for(int i=0;i<len1;i++){
                for(int j=0;j<len2;j++){
                    int state = board[i][j];
                    //v[i][j] = 1;
                    
                    res = 0;
                    for(auto it:dir){
                        int nx = i + it.first, ny = j + it.second;
                        if(nx<0 || ny<0 || nx>=len1 || ny>=len2)
                            continue;
                        if(v[nx][ny] == 1){
                            res = res + (board[nx][ny]+1)%2;
                        }
                        else
                            res += board[nx][ny];
                    }
                    if(state == 1){
                        if(res<2 || res >3){
                            board[i][j] = 0;
                            v[i][j] = 1;
                        }
                    }
                    else{
                        if(res == 3){
                            board[i][j] = 1;
                            v[i][j] = 1;
                        }
                    }
                }
            }
            return;
        }
    };
    

Log in to reply
 

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