sourcecode

Wednesday, January 2, 2013

Sudoku Solver


Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
class Solution {
    vector<vector<char> > b;
    bool checkRow(int row, char val){
        for(int ii = 0; ii < 9; ++ii){
            if (b[row][ii] == val) return false;
        }
        return true;
    }
    
    bool checkCol(int col, char val){
        for(int ii = 0; ii < 9; ++ii){
            if (b[ii][col] == val) return false;
        }
        return true;
    }
    
    bool checkBlock(int row, int col, char val){
        row = row/3*3;
        col = col/3*3;
        for(int ii = row; ii < row+3; ++ii){
            for(int jj = col; jj < col+3; ++jj){
                if (b[ii][jj] == val) return false;
            }
        }
        return true;
    }
    
    bool process(int row, int col){
        int index = row*9 + col;
        if (index > 80) return true;
        int next_index = index+1;
        int next_row = next_index/9;
        int next_col = next_index - next_row*9;
        if (b[row][col] == '.'){
            for(int ii = '1'; ii <= '9'; ++ii){
                if (checkRow(row,ii) && checkCol(col,ii) && checkBlock(row,col,ii)){
                    b[row][col] = ii;
                    if(process(next_row, next_col)) return true;
                    else{
                        b[row][col] = '.';
                    }
                }
            }
            return false;
        }else{
           return process(next_row, next_col);
        }
    }
public:
    void solveSudoku(vector<vector<char> > &board) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        b = board;
        process(0,0);
        board = b;
        return;
    }
};

No comments: