Any better O(1) space code?


  • 1
    R

    do you have idea how to improve this code?

    class Solution {
    public:
        bool isValidSudoku(vector<vector<char>>& board) {
            // check rows
            int len=board.size();
            for(int i=0; i<len; ++i){
                int taken=0;
                for(int j=0; j<len; ++j){
                    if(board[i][j]=='.') continue;
                    int num=board[i][j]-1;
                    if((taken>>num) & 1) return false;
                    taken |= (1<<num);
                }
            }
            
            // check columns
            for(int i=0; i<len; ++i){
                int taken=0;
                for(int j=0; j<len; ++j){
                    if(board[j][i]=='.') continue;
                    int num=board[j][i]-1;
                    if((taken>>num) & 1) return false;
                    taken|= (1<<num);
                }
            }
            
            // check squares
            for(int i=0; i<len; i+=3){
                for(int j=0; j<len; j+=3){
                    int taken=0;
                    for(int x=i; x<i+3; ++x)
                        for(int y=j; y<j+3; ++y){
                                if(board[x][y]=='.') continue;
                                int num=board[x][y]-1;
                                if((taken>>num)&1) return false;
                                taken|=(1<<num);
                        }
                }
            }
            return true;
        }
    };

Log in to reply
 

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