我正在尝试创建一个数独生成器,将拼图保存在二维字符串数组中。
我创建了一个在最后返回拼图的递归方法,但是一旦它返回拼图,它就会继续递归,所以我永远无法突破这个方法。
递归方法代码如下:
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);
如果有人对我需要修改的内容有任何建议,以便让此方法返回完整的数独谜题,那就太棒了。我已经有这个错误几天了,我不知道为什么。 :/
最佳答案
您可能需要检查 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;
}
关于c# - 使用递归方法的数独生成器算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22203353/