My code in C++ and just wondering if it's possible not using the left bit to store the new state?


  • 0
    Z
    class Solution {
    public:
        int neighbors(vector<vector<int>> &board, int i, int j){
            int m = board.size();
            int n = m ? board[0].size() : 0;
            int nei=0;
            for(int x=i-1;x<=i+1;x++) {
                for(int y=j-1;y<=j+1;y++) {
                    if(x>=0&&x<m&&y>=0&&y<n&&(x!=i||y!=j)) {
                        if(1&board[x][y])
                            nei++;
                    }
                }
            }
            return nei;
        }
        void gameOfLife(vector<vector<int>>& board) {
            int m = board.size();
            int n = m ? board[0].size() : 0;
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    int nei=neighbors(board,i,j);
                    if(nei==2){
                        board[i][j]= (board[i][j]<<1) | board[i][j];
                    }
                    if(nei==3){
                        board[i][j] |= 2;
                    }
                }
            }
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    board[i][j]>>=1;
                }
            }
        }
    };

Log in to reply
 

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