首页 > 解决方案 > 为什么我在数独求解器 C# 中不断收到 Stackoverflow 错误

问题描述

编辑:我真的很抱歉。我的错误在那里

    //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#recursionruntime-errorstack-overflowsudoku

解决方案


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

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


推荐阅读