标准9*9数独破解器

#include<bits/stdc++.h>
//#include<stdio.h>
//#include<string.h>
using namespace std;

int mmp[20][20];
char in[20];

void Print(){
    for(int i = 1;i <= 9;i ++){
        for(int j = 1;j <= 9;j ++){
            printf("%d",mmp[i][j]);
        }printf("
");
    }
    return ;
}

int check(int x,int y,int k){
    int a = (x + 2) / 3;
    int b = (y + 2) / 3;
    for(int i = 1;i <= 9;i ++){
        if(mmp[x][i] == k || mmp[i][y] == k){return 0;}
    }
    for(int i = 3 * a - 2;i <= 3 * a;i ++){
        for(int j = 3 * b - 2;j <= 3 * b;j ++){
            //printf("%d%d
",i,j);
            if(mmp[i][j] == k){return 0;}
        }
    }
    return 1;
}

void Last(){
    int a[10];
    memset(a,0,sizeof(a));
    for(int i = 1;i <= 9;i ++){
        a[mmp[9][i]] ++;
    }
    for(int i = 1;i <= 9;i ++){
        if(a[i] == 0){
            mmp[9][9] = i;
            return ;
        }
    }
    return ;
}

void dfs(int x,int y){
    if(x == 9 && y == 9){Last();Print();return ;}
    if(y == 10){x ++;y = 1;}
    //printf("%d %d
",x,y);
    //Print();
    if(mmp[x][y] == 0){
        for(int i = 1;i <= 9;i ++){
            if(check(x,y,i) == 0){continue;}
            mmp[x][y] = i;
            dfs(x,y + 1);
            mmp[x][y] = 0;
        }
    }
    else{
        dfs(x,y + 1);
    }

    return ;
}

int main(){
    memset(mmp,0,sizeof(mmp));
    for(int i = 1;i <= 9;i ++){
        scanf("%s",in);
        for(int j = 0;j < 9;j ++){
            if(in[j] <= '9' && in[j] >= '1'){
                mmp[i][j + 1] = in[j] - '0';
            }
        }
    }
    printf("
The solution is :

");
    dfs(1,1);
    return 0;
}
原文地址:https://www.cnblogs.com/love-fromAtoZ/p/9683879.html