【发布时间】:2012-11-15 21:40:53
【问题描述】:
所以我有这个大学任务来解决数独问题……我读到了关于算法 X 和跳舞算法的文章,但它们对我没有帮助。
我需要通过回溯来实现。我用维基百科给出的位置上的数字硬编码了二维数组中的一些索引(所以我确信它是可解决的)。
我得到的代码如下:
public void solveSudoku(int row, int col)
{
// clears the temporary storage array that is use to check if there are
// dublicates on the row/col
for (int k = 0; k < 9; k++)
{
dublicates[k] = 0;
}
// checks if the index is free and changes the input number by looping
// until suitable
if (available(row, col))
{
for (int i = 1; i < 10; i++)
{
if (checkIfDublicates(i) == true)
{
board[row][col] = i;
if (row == 8)
solveSudoku(0, col + 1);
else if (col == 8)
solveSudoku(row + 1, 0);
else
solveSudoku(row, col + 1);
board[row][col] = 0;
}
}
}
// goes to the next row/col
else
{
if (row == 8)
solveSudoku(0, col + 1);
else if (col == 8)
solveSudoku(row + 1, 0);
else
solveSudoku(row, col + 1);
}
}
/**
* Checks if the spot on the certain row-col index is free of element
*
* @param row
* @param col
* @return
*/
private boolean available(int row, int col)
{
if (board[row][col] != 0)
return false;
else
return true;
}
/**
* Checks if the number given is not already used in this row/col
*
* @param numberToCheck
* @return
*/
private boolean checkIfDublicates(int numberToCheck)
{
boolean temp = true;
for (int i = 0; i < dublicates.length; i++)
{
if (numberToCheck == dublicates[i])
{
temp = false;
return false;
}
else if (dublicates[i] == 0)
{
dublicates[i] = numberToCheck;
temp = true;
return true;
}
}
return temp;
}
我正在使用 StackOverflow
// goes to the next row/col
else
{
if (row == 8)
solveSudoku(0, col + 1);
else if (col == 8)
solveSudoku(row + 1, 0);
else
solveSudoku(row, col + 1);
}
这意味着我必须在某个时候停止递归,但我不知道该怎么做!
如果您在 solve() 函数中发现任何其他错误,请告诉我。因为我不确定我是否完全理解“回溯”的东西......
【问题讨论】:
-
Wiki too ;)
-
您应该查看您的复制代码。我不明白这如何检查一个数字是否被允许。你总是重置它(每次 SolveSudoku 调用),所以它会忘记一切。我也怀疑 9 个元素的数组如何检查所有内容
标签: java algorithm sudoku backtracking