My 0ms c++ solution using bit manipulation


  • 0
    Q
    void gameOfLife(vector<vector<int>>& board) {
        int direct[8][2]={{1,1},{-1,1},{1,-1},{-1,-1},{0,1},{1,0},{0,-1},{-1,0}};
        int row=board.size();
        if(row==0)
            return;
        int col=board[0].size();
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<col;j++)
            {
                int m=0;
                for(int k=0;k<8;k++)
                {
                    int ii=i+direct[k][0];
                    int jj=j+direct[k][1];
                    if((ii>=0)&&(ii<row)&&(jj>=0)&&(jj<col))
                    {
                        m<<=1;
                        m|=board[ii][jj]&1;
                        
                    }    
                }
                m<<=1;
                m|=board[i][j];
                board[i][j]=m;
            }
        }
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<col;j++)
            {
                int a=board[i][j]&1;
                board[i][j]>>=1;
                int b=0;
                while(board[i][j]!=0)
                {
                    b+=board[i][j]&1;
                    board[i][j]>>=1;
                }
                if(a==1)
                {
                    if(b<2)
                        board[i][j]=0;
                    else if(b>=2&&b<=3)
                        board[i][j]=1;
                    else
                        board[i][j]=0;
                }
                else if(a==0)
                {
                    if(b==3)
                        board[i][j]=1;
                    else
                        board[i][j]=0;
                }
            }
        }
    }

Log in to reply
 

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