Simple solution in C++ O(3 * 9 * 9) in time and space


  • 0
    M

    'r' checks the rows, 'c' checks the columns and 's' checks for the 3x3 squares.

    class Solution {
    public:
        bool isValidSudoku(vector<vector<char> > &b) {
            bool r[9][9], c[9][9], s[3][3][9];
            memset(r, false, sizeof r);
            memset(c, false, sizeof c);
            memset(s, false, sizeof s);
            int i, j;
            char car;
            for(i = 0; i < 9; i++){
                for(j = 0; j < 9; j++){
                    if(b[i][j] > '0' && b[i][j] <='9'){
                        car = b[i][j] - '1';
                        if(r[i][car]) return false;
                        r[i][car] = true;
                        if(c[j][car]) return false;
                        c[j][car] = true;
                        if(s[i/3][j/3][car]) return false;
                        s[i/3][j/3][car] = true;
                    }
                }
            }
            return true;
        }
    };

Log in to reply
 

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