C ++中数独实现的分段错误

时间:2015-04-22 00:24:29

标签: c++ segmentation-fault sudoku

我必须制作一个n x n数独求解器。用户输入n,然后输出是解决的数独谜题。我做了大部分,但我一直遇到分段错误。任何帮助将不胜感激。 我认为这与我的递归函数有关。

int findValues(int** sudoku, int size, int a[], int r, int c)
{
    int n=0;
    int i,j;
    int s=(int)(sqrt(size));
    int b[size+1];
    memset(b,0,size*size*sizeof(int));

    //checks numbers in row
    for(i=0; i<size; i++)
        b[sudoku[r][i]]=1;

    //checks number in column
    for(i=0; i<size; i++)
        b[sudoku[i][c]]=1;

    //checks number in block
    r=(r/s)*s;
    c=(c/s)*s;
    for(i=r; i<r+s; i++)
        for(j=c; j<c+s;j++)
            b[sudoku[i][j]]=1;

    //Fill array a[] with no.s disappeared in current row, column and block
    for(i=1;i<=size; i++)
        if(!b[i])
            a[n++]=i;

    return n;
}

//Function to solve the sudoku board
void Solve(int size, bool &stop)
{
    int** sudoku;
    sudoku=new int*[size];
    for(int z=0; z<size; z++)
        sudoku[z] = new int[size];

    int i,j;
    int a[size+1];
    memset(a,0,size*size*sizeof(int));
    int n=0;

    if(stop) //true if user does not want more solutions
        return;

    if(isFull(sudoku, size))    //true if now sudoku board is solved completely
    {
        //shows the solution        
        displaySolution(sudoku, size);
        char more;
        cout << "Press 0 for 'END'\n";
        cin >> more;

        if(more != '1')
            stop = true;
        return;//so that only one solution will appear, and it does not       continuously repeat       
    }

    //to find empty place
    int y = 0;
    for(i=0;i<size;i++)
    {
        for(j=0;j<size;j++)
            if(!sudoku[i][j])
            {
                y = 1;
                break;
            }
        if(y)
            break;
    }

    //check all values at that place
    n = findValues(sudoku, size, a, i, j);
    for(int l=0;l<n;l++)
    {
        //put value at vacant place
        sudoku[i][j]=a[l];
        //now solve the updated board
        Solve(size, stop);
    }

    sudoku[i][j]=0;
}

1 个答案:

答案 0 :(得分:1)

int a[size+1];
memset(a,0,size*size*sizeof(int));

这会导致段错误。您正在将内存的大小平方清除到正常大小的数组上。

除了你制作数独板时创建的所有内存泄漏。你的尺寸+ 1的东西也感觉非常hacky,也不需要。