数独求解器在C++部分求解

Sudoku Solver in C++ partially solving

本文关键字:C++      更新时间:2023-10-16

我最近用 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 sudokon";
      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 locationn";
      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";
              }
          }
     }

sudoko(int, int)中,您执行两次递归调用,然后在不返回值的情况下退出函数,这是未定义的行为。您可能希望用 return sudoko(...) 替换每个调用,并启动编译器警告。

相关文章:
  • 没有找到相关文章