这是我的后跟踪逻辑代码。
private void backtrackLogic()
{
if (m == 0 && n != 0)
{
n--;
m = 8;
if(sudokuArray[n, m] == 0)
{
counter = copyArray[n, m];
copyArray[n, m] = 0;
if(counter == 9)
{
backtrackLogic();
}
}
else
{
backtrackLogic();
}
}
else if (m != 0)
{
m--;
if (sudokuArray[n, m] == 0)
{
counter = copyArray[n, m];
copyArray[n, m] = 0;
if (counter == 9)
{
backtrackLogic();
}
}
else
{
backtrackLogic();
}
}
else
{
Environment.Exit(0);
}
}
这是我的算法其余部分的代码。
private void SolveButton_Click(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
copyArray[i, j] = sudokuArray[i, j];
Console.Write(sudokuArray[i, j]);
}
}
counter = 1;
bool noOptions = false;
for (n = 0; n < 9; n++)
{
for (m = 0; m < 9; m++)
{
for (counter = 1; counter < 10; counter++)
{
if (sudokuArray[n, m] == 0)
{
if (checkRow(n, m, counter) && checkColumn(n, m, counter) && checkBox(n, m, counter))
{
copyArray[n, m] = counter;
printTextBox(n, m, counter);
Console.Write(counter);
break;
}
else if (counter == 9)
{
noOptions = true;
}
}
if (noOptions)
{
backtrackLogic();
noOptions = false;
}
}
}
}
for (int n = 0; n < 9; n++)
{
for (int m = 0; m < 9; m++)
{
Console.Write(copyArray[n, m]);
}
}
}
在困难的Sudoku问题上运行此代码时,程序会因执行所需的时间而超时。任何执行算法的帮助都会非常有用!