数独求解算法中的随机性

Randomness in Sudoku solving algorithm

我正在使用这个回溯数独求解算法,它非常好而且高效

    private void solve()
    {
        for (var y = 8; y >= 0; y--)
        {
            for (var x = 8; x >= 0; x--)
            {
                var a = grid[y, x];
                if (a == 0)
                {
                    for (var n = 1; n <= 9; n++)
                    {
                        if (possible(y, x, n))
                        {
                            grid[y, x] = n;
                            solve();
                            grid[y, x] = 0;
                        }
                    }
                    return;
                }
            }
        }
        print();
    }

问题是我想添加一个我没能做到的小改动,而不是按顺序尝试数字 1 到 9,我希望它从 1 到 9 中选择一个随机数,然后将其设置在网格中,当然不会重复。

public static class MyRandomGenerator
{
    private static Random random = new Random();

    public static int[] Generate(int inclusiveMinValue, int exclusiveMaxValue)
    {
        if (exclusiveMaxValue <= inclusiveMinValue)
            throw new ArgumentException(nameof(exclusiveMaxValue));

        var capacity = exclusiveMaxValue - inclusiveMinValue;
        var result = new HashSet<int>(capacity);

        while (result.Count < capacity)
        {
            result.Add(random.Next(inclusiveMinValue, exclusiveMaxValue));
        }

        return result.ToArray();
    }            
}