Sudoku generator algorithm using a recursive method

I'm trying to create a Sudoku generator that saves the puzzle in a 2D string array.

I created a recursive method that returns the puzzle at the end, but as soon as it returns the puzzle it continues with the recursion and so I can never break out of this method.

The recursive method code is below:

    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?
    }

Here's how I'm calling this method:

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

If anyone has any suggestions as to what I need to modify in order to get this method to return a complete sudoku puzzle that'd be awesome. I've had this bug for a few days now and I can't figure out why. :/


You probably need to check if the return value from RecursiveFill() is non-null, and return it if it is.

In your inner loop:

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;
}
链接地址: http://www.djcxy.com/p/96164.html

上一篇: 这个算法用于解决Sudoku的时间复杂度是多少?

下一篇: 使用递归方法的数独生成器算法