Sudoku Solver

Sudoku Solver

The main approach is DFS traversal. Fill in numbers 1-9, then use preprocessed constraints to prune the search space.

class Solution {
public:
    void solveSudoku(vector<vector<char>>& board) {
        memset(row, 0, sizeof row);
        memset(col, 0, sizeof col);
        memset(box, 0, sizeof box);
        // Preprocess to get constraint table, use this to prune during search
        for(int i=0;i<9;++i) {
            for(int j=0;j<9;++j) {
                if (board[i][j]=='.') continue;
                int n=board[i][j]-'0';
                row[i][n]=1;
                col[j][n]=1;
                box[(i/3)*3+j/3][n]=1;
            }
        }
        
        DFS(board, 0, 0);
    }
    
    bool DFS(vector<vector<char>>& bd, int x, int y) {
        // x equals 9 means solution found
        if (x==9) return true;
        // Next cell
        int ny=(y+1)%9;
        int nx=(ny==0) ? x+1:x;
        
        if (bd[x][y]!='.') return DFS(bd, nx, ny);
        for(int n=1;n<=9;++n) {
            if (!row[x][n] && !col[y][n] && !box[(x/3)*3+y/3][n]) {
                row[x][n]=1;
                col[y][n]=1;
                box[(x/3)*3+y/3][n]=1;
                bd[x][y]=n+'0';
                // Stop searching if found
                if (DFS(bd, nx, ny)) return true;
                bd[x][y]='.';
                row[x][n]=0;
                col[y][n]=0;
                box[(x/3)*3+y/3][n]=0;
            }
        }
        return false;
    }
    
private:
    int row[9][10];
    int col[9][10];
    int box[9][10];
};

#DFS