所以我有这个大学的任务来解决Sudoku ...我读了关于算法X和跳舞算法,但他们没有帮助我。Sudoku algorithm with backtracking - java
我需要使它回溯。我用二维数组中的一些索引对Wikipedia提供的地方进行了硬编码(所以我相信它是可以解决的)。
我得到的代码如下:
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;
}
我正在上
// 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);
}
这意味着我必须停止在某一点上递归的StackOverflow,但我想不通它如何! 如果您在solve()
功能中发现任何其他错误 - 请告诉我。因为我不知道我完全理解的“回溯”的事情......
http://www.byteauthor.com/2010/08/sudoku-solver/有一个很好的例子。 – chAmi
[Wiki too](http://en.wikipedia.org/wiki/Sudoku_algorithms#Backtracking);) – sp00m
你应该看看你的dublicates代码。我不明白这可以检查是否允许一个数字。你总是重置它(每个SolveSudoku调用),所以它忘记了一切。我也怀疑9个元素如何检查所有东西 – Origin