【问题标题】:Using Recursion/Backtracking to create and solve a sudoku puzzle使用递归/回溯创建和解决数独难题
【发布时间】:2014-03-18 11:47:25
【问题描述】:

对于我的计算机课,我的老师希望我们使用递归或回溯来创建和解决 nXn 大小的数独难题。拼图必须是动态分配的,拼图的唯一规则是任何行或列都不能重复。对角线和较小的子正方形可以有重复。这是我到目前为止所写的内容。

#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;


void fill_puzzle(int **array, int size);
void delete_puzzle(int array, int size);
bool check_filled(int **array, int size);

bool check_correct(int **array, int size){
    int temp=0;
    for(int i=0; i<size; i++){
        for (int j=0; j<size; j++){
            for (int k=0;k<size;k++){
                if (array[i][k]==array[i][j])
                    return false;
                else
                    return true;
            }
        }
    }
}           

void fill_puzzle(int **array, int size){
    srand(time(NULL));
    int random_number;
    random_number=(rand()%size);
    while(check_correct(array,size)==false)
        for(int i=0; i<size; i++){
            for (int j=0; j<size; j++){
                array[i][j]=random_number;
                if (check_correct(array, size) ==false)
                    fill_puzzle(array, size);
                else
                    cout << array[i][j];
            }
        }                   
}

void delete_puzzle(int **array, int size){
for (int i=0; i<size; i++){
    delete [] array[i];
}
delete []array;
}

int main(){
int  size=0;
int **array;
cout << "Hello, what size puzzle would you like to create? Please type 1 number. Example: 3 would make a 3x3 sudoku puzzle."<<endl;
cin >> size;
if (size <= 0){
    cout << "The size you have chosen will not work, please choose a number greater than 0." << endl;
    cin >> size;
    for (int i=0; i<size; i++){
    array=new int*[size];
    array[size]=new int [size];

}
}
else {
    for (int i=0; i<size; i++){
    array=new int*[size];
    array[size]=new int [size];
}
fill_puzzle(array,size);
delete_puzzle(array, size);


}
return 0;
}

当我尝试编译时,我得到一个分段错误,并且使用 GDB 它说错误发生在 if (array[i][k]==array[i][j]) 行的 check_correct 中。提前致谢。

【问题讨论】:

  • 编译不会给你一个分段错误,你正在运行它。
  • 是的,我就是这个意思

标签: c++ recursion sudoku backtracking


【解决方案1】:

到目前为止,我可以看到,为二维数组分配内存的代码不正确,分段错误是由于您没有正确分配而访问非法内存造成的。

for (int i=0; i<size; i++){
    array=new int*[size]; // move it out of loop
    array[size]=new int [size]; //array[size]?!

试试这个:

    array = new int*[size];
    for(int i = 0; i < size; ++i)
        array[i] = new int[size];

在您的数独求解器中还有其他问题(fill_puzzle() 陷入无限递归,它会导致您的堆栈越来越大,直到出现分段错误),请使用调试器来解决它。

【讨论】:

  • 为了简单起见,我想避免在我的程序中使用类,但是创建一个类会更容易吗?
  • 不需要这么简单的程序。
  • 哇,我什至没有想到我使用的是 array[size] 而不是 array[i]。我太傻了,谢谢你
  • 还有一个问题,我使用srand和rand的方式有问题吗? GDB 说这个功能有问题。 @jfly
  • 没问题,如果要隐藏警告,添加演员表:srand((unsigned int)time(NULL))
猜你喜欢
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
  • 2014-05-08
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多