HDU-1426 Sudoku Killer(搜索)

题目链接:Problem - 1426 (hdu.edu.cn)

题目:

题目样例:

 

 题目思路:

暴力搜索,对每一个问号进行填入尝试,对横和纵的进行判断,对矩形也要进行判断,在第几个矩形,需要判断(横和纵都要除三);

AC:

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
const int N=15;
char a[N][N];
bool check(int x,int y,char sum){
    for(int i=1;i<=9;i++){
        if(a[x][i]==sum||a[i][y]==sum)return false;
    }
    int l=x/3;
    if(x%3!=0)l++;
    int r=y/3;
    if(y%3!=0)r++;
    for(int i=(l-1)*3+1;i<=l*3;i++){
        for(int j=(r-1)*3+1;j<=r*3;j++){
            if(a[i][j]==sum)return false;
        }
    }
    return true;
}
bool dfs(){
    for(int i=1;i<=9;i++){
        for(int j=1;j<=9;j++){
            if(a[i][j]!='?'){
                continue;
            }else{
                for(char k='1';k<='9';k++){
                    if(check(i,j,k)){
                        a[i][j]=k;
                        if(dfs()){
                            return true;
                        }else{
                            a[i][j]='?';
                        }
                    }
                }
                return false;
            }
        }
    }
    return true;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    int sum=0;
    while(cin>>a[1][1]){
        if(sum>0)cout<<endl;
        for(int i=1;i<=9;i++){
            for(int j=1;j<=9;j++){
                if(i==1&&j==1){
                    continue; 
                }else{
                    cin>>a[i][j];
                }
            }
        }
        dfs();
        for(int i=1;i<=9;i++){
            for(int j=1;j<=9;j++){
                cout<<a[i][j];
                if(j!=9)cout<<" ";
            }
            cout<<endl;
        }
        sum++;
    } 
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/m0_63569670/article/details/127857019