簡體   English   中英

數獨 C 遞歸函數無法正常工作

[英]Sudoku C recursive function not working properly

我在 c 中做了一個數獨求解器,我的遞歸函數只適用於第一行而不是停止。 它查找值為零的第一個元素並填充它,然后查找下一個值,並用另一個解決方案填充它。 在它解決了它停止的第一行之后,我將如何啟用canSolve ,遞歸函數遍歷整個板...... sudokuGrid也是全局的。

//this function makes a list of possible values for an empty cell, candidateList.
//candidateList is global so it  the list can be accesed by the recursive solver function:
//canSolve();
void verifyCell(int x, int y){
    int i;
    int j;

    for (i=0; i<9; i++){
        candidateList[i] = 0;
    }
    //Rows
    for (j=0; j<cols; j++){
        if(sudokuGrid[x][j] != 0){
           candidateList[sudokuGrid[x][j] - 1] = 1;
        }
    }
    //Columns
   for (i=0; i<rows; i++){
        if(sudokuGrid[i][y] != 0){
           candidateList[sudokuGrid[i][y] - 1] = 1;
        }
    }
    //blocks
    int startRow = ((x/3)*3);
    int startCol = ((x/3)*3);
    for (i = startRow; i<startRow+3; i++){
        for(j=startCol;j<startCol+3;j++){
            if(sudokuGrid[i][j] != 0){
               candidateList[sudokuGrid[i][j] - 1] = 1;
            }
       }
    }
    for(i = 0; i<9;i++){
        if (candidateList[i]==0){
            candidateList[i] = i+1;
        }else{
            candidateList[i] = 0;
        }
    }
    return;
}

 canSolve(){
    int i;
    int j;
    int x;
    int y;
    x= 0;
    y = 0;
    //gridToString();
    if (isSolved()==1){
        printf("Great this grid is Solved!\n");
        gridToString();
        return;
    }
    for(i=0;i<rows;i++){
        for(j=0;j<cols;j++){
            if(sudokuGrid[i][j]==0){
                x=i;
                y=j;
            }
        }
        goto rest;
    }
    printf("(%d, %d)", x, y);
    rest:;
    verifyCell(x,y);

    for(i = 0; i<rows; i++){
        printf("%d", candidateList[i]);
        if (candidateList[i] != 0){
            sudokuGrid[x][y]=candidateList[i];
            gridToString();
            canSolve();//By the end of solving the first row it stops
        }else{
            sudokuGrid[x][y]=sudokuGrid[x][y];
        }
    }
}

將遞歸與全局變量結合使用通常不是一個好主意。 如果您的求解器做出了錯誤的選擇並且需要回溯,它還需要將電路板恢復到它做出該選擇時的狀態。

那么你需要做什么?

我想你需要在嘗試下一個候選人之前擦拭董事會的其余部分:

        canSolve();//By the end of solving the first row it stops
        wipeRestOfBoard(x,y);  // Put 0 in sudokuGrid[x,y] and subsequent positions
    }else{

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM