c++ - C++ 中的数独求解器部分求解

标签 c++ sudoku recursive-backtracking

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

最佳答案

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

关于c++ - C++ 中的数独求解器部分求解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28071688/

相关文章:

C++ 如何打印复合 vector 的内容

java - 调用静态 JNI 方法以从 C++ 返回字符串

Java 数独解算器抛出除以零 ArithmeticException

c - 数独生成器导致段错误

recursion - 用特定票据表示金额

c - 我在用 C 语言求解数独的递归回溯算法时遇到问题

c++ - 在 C++ 中创建对象的动态数组、删除对象和释放内存

c++ - 从文本文件中读取数据

java - 将Matlab程序转换为Java以提高性能的敏感性

c++ - 为什么以下代码会返回错误的计数值?