-2
我在c中製作了一個數獨求解器,而遞歸函數只對第一行起作用,而不是停止。它尋找值爲零的第一個元素並填充它,然後查找下一個值,並用另一個解決方案填充它。在它解決了第一行之後,我將如何啓用canSolve
,遞歸功能貫穿整個董事會...... sudokuGrid
也是全球性的。數獨C遞歸函數無法正常工作
//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];
}
}
}
使用調試器來看看會發生什麼。或者閱讀代碼做爲「精神鍛鍊」的內容。你一定會發現一些錯誤。 –