LeetCode题解——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...

class Solution {
public:
    bool col[10][10],row[10][10],f[10][10];
    bool flage=false;
    void solveSudoku(vector<vector<char>>& board) {
        memset(col,false,sizeof(col));
        memset(row,false,sizeof(row));
        memset(f,false,sizeof(f));
        for(int i=0; i<9; i++){
            for(int j=0; j<9; j++){
                if(board[i][j]!='.'){
                    int num=board[i][j]-'0';
                    int k = (i/3)*3+j/3;
                    row[i][num]=col[j][num]=f[k][num]=true;
                }
            }
        }
        dfs(board,0,0);
    }
    void dfs(vector<vector<char>>& board,int i,int j){
        if(flage) return;
        if(i>=9){ flage=true; return;}
        if(board[i][j]!='.'){
            if(j<8) dfs(board,i,j+1);
            else dfs(board,i+1,0);
            if(flage) return;
        }
        else{
            int k = (i/3)*3+j/3;
            for(int n=1;n<=9;n++){
                if(!row[i][n] && !col[j][n] && !f[k][n]){
                    board[i][j]='0'+n;
                    row[i][n]=col[j][n]=f[k][n]=true;
                    if(j<8) dfs(board,i,j+1);
                    else dfs(board,i+1,0);
                    if(flage) return;
                    row[i][n]=col[j][n]=f[k][n]=false;//一次尝试失败,重置,回溯
                } 
            }
            board[i][j]='.';//当所有尝试都失败时,重置,回溯
        }
    }
};


你可能感兴趣的:(LeetCode,backtracking)