【发布时间】:2019-05-09 05:15:29
【问题描述】:
编辑:我真的很抱歉。我的错误在那里
//get unassigned position
unassignedPos = GetNextUnassignedValue(matrix);
int col = unassignedPos.Item1;
int row = unassignedPos.Item2;
row 必须是 item1,col 必须是 item2... 还发现我用数独尝试过,但无法正确解决。
我是 C# 新手,刚刚开始更深入地编写代码。有谁知道为什么我在以下代码示例中不断收到 Stackoverflow 错误?我仔细检查并重新排列了约束,它们应该没问题。
class SudokuCalc
{
(int, int) finish = (9, 9);
(int, int) unassignedPos = (0, 0);
//method to recursively solve the sudoku
public bool Solve(int[,] matrix)
{
//if we are at the finish position return true
if (finish.Item1 == GetNextUnassignedValue(matrix).Item1
&& finish.Item2 == GetNextUnassignedValue(matrix).Item2)
{
return true;
}
//get unassigned position
unassignedPos = GetNextUnassignedValue(matrix);
int col = unassignedPos.Item1;
int row = unassignedPos.Item2;
//go through all possible values
for (int value = 1; value <= 9; value++)
{
if (IsValid(matrix, row, col, value))
{
matrix[row, col] = value;
//recursively try to solve
if (Solve(matrix))
{
return true;
}
// if we couldnt solve the sudoku
// set the previous value 0 and try again
matrix[row, col] = 0;
}
}
return false;
}
【问题讨论】:
-
您是否尝试过逐行浏览代码并观察它的实际作用?
标签: c# recursion runtime-error stack-overflow sudoku