Leetcode Sudoku Solver

OpenSoucre發表於2014-07-07

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...

 

遇到九宮格問題一般都深搜解決

class Solution {
public:
    bool isValidRow(int row , vector<vector<char> >& board){
        vector<int> cnt(10,0);
        for(int col = 0; col < 9; ++ col){
            char item = board[row][col];
            if(item != '.'){
                if(cnt[item-'0']!=0) return false;
                else cnt[item-'0']++;
            }
        }
        return true;
    }
    
    bool isValidCol(int col, vector<vector<char> >& board ){
        vector<int> cnt(10,0);
        for(int row = 0; row < 9; ++ row){
            char item = board[row][col];
            if(item != '.'){
                if(cnt[item-'0']!=0) return false;
                else cnt[item-'0']++;
            }
        }
        return true;
    }
    
    bool isValidBox(int i,int j, vector<vector<char> >& board){
        vector<int> cnt(10,0);
        for(int row = 3*i;row < 3*i+3; ++row){
            for(int col = 3*j; col < 3*j+3; ++col){
                char item = board[row][col];
                if(item != '.'){
                    if(cnt[item-'0']!=0) return false;
                    else cnt[item-'0']++;
                }
            }
        }
        return true;
    }

    bool isValidSudoku(int x, int y,vector<vector<char> > &board) {
        return isValidRow(x,board)&&isValidCol(y,board)&&isValidBox(x/3,y/3,board);
    }
    
    bool dfs(int pos ,vector<vector<char> >& board){
        int n = board.size();
        if(pos == n*n) return true;
        int x = pos/n, y = pos%n;
        if(board[x][y]=='.'){
            for(char i = '1'; i<='9';++ i){
                board[x][y]=i;
                if(isValidSudoku(x,y,board) && dfs(pos+1,board)) return true;
                board[x][y]='.';
            }
        }else{
            if(dfs(pos+1,board)) return true;
        }
        return false;
    }
    
    void solveSudoku(vector<vector<char> > &board) {
        dfs(0,board);
    }
};

 

相關文章