使用递归方法的Sudoku生成器算法

时间:2014-03-05 16:23:45

标签: c# algorithm recursion generator sudoku

我正在尝试创建一个Sudoku生成器,将拼图保存在2D字符串数组中。

我创建了一个递归方法,最后返回拼图,但是一旦它返回拼图,它就会继续递归,所以我永远不会破坏这种方法。

递归方法代码如下:

    static string[,] RecursiveFill(int digit, int px, int py, string[,] grid)
    {
        // Create a new test grid
        string[,] testGrid = new string[9, 9];

        // Fill it with the current main grid
        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
                testGrid[j, i] = grid[j, i];
        }

        // Place the digit to be entered into the test grid
        testGrid[px, py] = digit.ToString();

        // Find a new digit to enter
        for (int x = 0; x < 9; x++) // Iterate through the grid by x
        {
            for (int y = 0; y < 9; y++) // And by y
            {
                if (testGrid[x, y] == 0.ToString() || testGrid[x, y] == null) // If an empty slot
                {
                    for (int val = 1; val <= 9; val++) // 1-9 as these are the numbers to enter
                    {
                        if (CheckMove(y, x, val, testGrid)) // If the move is valid
                            RecursiveFill(val, x, y, testGrid); // Use recursion and go back around
                    }

                    return null; // Otherwise return null
                }
            }
        }

        return testGrid; // This gets returned but then it carries on with the RecursiveFill method and never exits this method?
    }

以下是我如何调用此方法:

    sudokuGrid = RecursiveFill(0, 0, 0, sudokuGrid);

如果有人对我需要修改什么有任何建议,以便让这个方法返回一个非常棒的完整的数独谜题。我已经有几天这个bug了,我无法弄清楚原因。 :/

1 个答案:

答案 0 :(得分:2)

您可能需要检查RecursiveFill()的返回值是否为非空,如果是,则返回。

在你的内循环中:

if (CheckMove(y, x, val, testGrid)) // If the move is valid
{
    var result = RecursiveFill(val, x, y, testGrid); // Use recursion and go back around

    if (result != null)
        return result;
}
相关问题