我已经在这里寻求帮助,但没有人回答,这真的很令人沮丧,我正在尝试编写一个代码来解决递归函数中的数独(回溯),这里是代码:
#include <stdio.h>
#include <windows.h>
#define SIZE 9
#define SQUARE_SIZE 3
void print(int arrBoard[SIZE][SIZE])
{
system("cls");
int i, j;
for (i = 0; i < SIZE; i++)
{
if (i % 3 == 0) printf("_ _ _ _ _ _ _ _ _ _ _ _\n");
for (j = 0; j < SIZE; j++)
{
if (j % 3 == 0) printf("| ");
printf("%d ", arrBoard[i][j]);
}
printf("\n");
}
Sleep(100);
}
BOOL IsValidRow(int arrBoard[SIZE][SIZE], int iNum, int iRow)
{
int iCol;
for (iCol = 0; iCol < SIZE; iCol++)
if (arrBoard[iRow][iCol] == iNum) return FALSE;
return TRUE;
}
BOOL IsValidCol(int arrBoard[SIZE][SIZE], int iNum, int iCol)
{
int iRow;
for (iRow = 0; iRow < SIZE; iRow++)
if (arrBoard[iRow][iCol] == iNum) return FALSE;
return TRUE;
}
BOOL IsValidSquare(int arrBoard[SIZE][SIZE], int iNum, int iRow, int iCol)
{
iRow-= (iRow % SQUARE_SIZE);
iCol-= (iCol % SQUARE_SIZE);
int i, j;
for(i = 0; i < SQUARE_SIZE; i++)
for (j = 0; j < SQUARE_SIZE; j++)
if (arrBoard[iRow + i][iCol + j] == iNum) return FALSE;
return TRUE;
}
BOOL IsValid(int arrBoard[SIZE][SIZE], int iNum, int iRow, int iCol)
{
if (IsValidRow(arrBoard, iNum, iRow) == FALSE) return FALSE;
if (IsValidCol(arrBoard, iNum, iCol) == FALSE) return FALSE;
if (IsValidSquare(arrBoard, iNum, iCol, iRow) == FALSE) return FALSE;
return TRUE;
}
BOOL _Solve(int arrBoard[SIZE][SIZE], int iRow, int iCol)
{
if (iRow == 9) return TRUE;
if (arrBoard[iRow][iCol])
{
iRow = (iCol == 8) ? iRow + 1 : iRow;
iCol = (iCol == 8) ? 0 : iCol + 1;
if(_Solve(arrBoard, iRow, iCol)) return TRUE;
return FALSE;
}
int iNewNum, iOldRow, iOldCol;
for (iNewNum = 1; iNewNum <= SIZE; iNewNum++)
{
if (IsValid(arrBoard, iNewNum, iRow, iCol))
{
arrBoard[iRow][iCol] = iNewNum;
print(arrBoard);
iOldRow = iRow; iOldCol = iCol;
iRow = (iCol == 8) ? iRow + 1 : iRow;
iCol = (iCol == 8) ? 0 : iCol + 1;
if (_Solve(arrBoard, iRow, iCol)) return TRUE;
iRow = iOldRow; iCol = iOldCol;
arrBoard[iRow][iCol] = 0;
}
}
return FALSE;
}
int main(void)
{
int arrBoard[SIZE][SIZE] =
{0, 1, 0, 3, 6, 4, 0, 2, 0,
6, 0, 0, 0, 0, 0, 0, 9, 7,
0, 0, 0, 9, 0, 7, 0, 0, 0,
0, 0, 6, 1, 0, 2, 8, 0, 0,
1, 9, 8, 0, 0, 0, 0, 3, 2,
0, 0, 7, 8, 0, 3, 9, 0, 0,
0, 0, 0, 7, 0, 8, 0, 0, 0,
4, 0, 0, 0, 0, 0, 0, 0, 3,
0, 2, 0, 4, 5, 6, 0, 1, 0};
_Solve(arrBoard, 0, 0);
fflush(stdin);
getchar();
return 0;
}
它不是真正的代码(只是因为 UI 现在不重要)。所以我在这里所做的就是在每次更改任何单元格时打印电路板。我在尝试解决时看到了一个错误,当它到达第 2 行的单元格时:2 col: 6(在其 [1][5] 的索引中),它跳过数字 1(这是真正的答案),因为它没有尝试过,它不能解决剩下的数独。我不知道为什么它不起作用。