【问题标题】:Why do i keep getting Stackoverflow Error in Sudoku Solver C#为什么我在数独求解器 C# 中不断收到 Stackoverflow 错误
【发布时间】: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


【解决方案1】:

在当前情况下,StackOverflow 异常意味着您的 Solve 方法递归调用自身的次数过多。发生这种情况时,您可以停止调试器并查看包含大量嵌套 Solve 调用的所有堆栈跟踪。

在您的条件下,您有一些极端情况会强制代码无限调用Solve 方法。要跟踪您可以在 Solve 方法的开头添加日志记录并写入调用您的磁盘矩阵。可能在某些时候你会一遍又一遍地获得相同的价值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2022-09-23
    • 2022-11-01
    • 2014-04-12
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    相关资源
    最近更新 更多