我最近用c ++制作了一个数独求解器。我使用了一个回溯算法来解决它,但是有一个问题:在某些情况下它只能解决到第5行。
工作案例:[6] [6] = 2,[4] [5] = 1
第5行后的案例失败:[1] [1] = 1
我不知道在某些情况下部分解决sudoko的原因可能是什么,并且存在这种情况的解决方案
using namespace std;
#include<iostream>
int a[9][9],b[9][9];
bool searchrow(int i,int w,int p){
int q=0;
for(int j=0;j<9;j++){
if(j==w){
continue;
}
if(a[i][j]==p){
q=1;break;
}
}
if(q==1){
return false;
}
else
return true;
}
bool searchcoloumn(int i,int w,int p){
int q=0;
for(int j=0;j<9;j++){
if(j==w){
continue;
}
if(a[j][i]==p){
q=1;break;
}
}
if(q==1){
return false;
}
else
return true;
}
bool searchmatrix(int i,int j,int p){
int m,n,x,y,l,k,q;
m=(i/3)*3;
n=(j/3)*3;
x=m+2;
y=n+2;
q=0;
for(l=m;l<=x;l++){
for(k=n;k<=y;k++){
if(l==i&&k==j){ //skip the current location
continue;
}
if(a[l][k]==p){
q=1;
break;
}
}
}
if(q==0){
return true;
}
else
return false;
}
bool place(int i,int j,int p){
if(searchrow(i,j,p)&&searchcoloumn(j,i,p)&&searchmatrix(i,j,p)){
return true;
}
else{
return false;
}
}
bool sudoko(int i,int j){
int w,x;
for(int p=1;p<10;p++){
x=0;
if(place(i,j,p)){
if(b[i][j]==0){
a[i][j]=p;
}
if((i==8)&&(j==8)){
return true;
}
else if(j==8){
sudoko(i+1,0);
}
else{
sudoko(i,j+1);//move to next coloumn
}
}
}
}
int main(){
int i,j,t,data;
cout<<"\nEnter how many no. to add to sudoko\n";
cin>>t;//t is the no of element which are initially present in sudoko and user should give as input
cout<<"\nEnter row , coloumn and then data at the respective location\n";
for(int m=0;m<9;m++){
for(int n=0;n<9;n++){
a[m][n]=0;
b[m][n]=0;
}
}
while(t--){
cout<<"Enter row";
cin>>i;
cout<<"Enter coloumn";
cin>>j;
cout<<"Enter data";
cin>>data;
a[i][j]=data;
b[i][j]=data;
}
if(sudoko(0,0));//used a semicolon here so that to display result
for(int p=0;p<9;p++){
cout<<"\n"
for(int q=0;q<9;q++){
cout<<a[p][q]<<"\t";
}
}
}
答案 0 :(得分:1)
在sudoko(int, int)
中,您执行两次递归调用,然后退出函数而不返回值,这是未定义的行为。您可能希望用return sudoko(...)
替换每个调用,并调高编译器警告。