0

最近、C++ で数独ソルバーを作成しました。バックトラッキング アルゴリズムを使用して解決しましたが、問題があります。場合によっては、5 行目までしか解決できません。

作業ケース : [6][6] = 2、[4][5] = 1

行 5 の後に失敗するケース: [1][1] = 1

一部のケースでスドコを部分的に解決している理由がわかりませんが、そのケースには解決策があります

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";
              }
          }
     }
4

1 に答える 1