Bit manipulation c++ solution


  • 0
    K
     class Solution {
    public:
    void gameOfLife(vector<vector<int>>& board) {
        int m=board.size();
        if(m==0)return;
        int n=board[0].size();
        for(int i=0; i < m; i++)
            for(int j=0; j < n; j++){
                int lives=0;
                for(int a=max(i-1, 0); a <= min(i+1, m-1); a++)
                {
                    for(int b=max(j-1, 0); b <= min(j+1, n-1 ); b++)
                        lives+=board[a][b] & 1;
                }
                if(lives==3 || (lives-board[i][j])==3)
                {
                    board[i][j]=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.