【发布时间】:2014-04-07 20:11:48
【问题描述】:
我正在尝试创建一个数独生成器,将谜题保存在二维字符串数组中。
我创建了一个递归方法,它在最后返回谜题,但一旦它返回谜题,它就会继续递归,所以我永远无法摆脱这个方法。
递归方法代码如下:
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);
如果有人对我需要修改什么以使此方法返回完整的数独难题有任何建议,那将是很棒的。我已经有这个错误几天了,我不知道为什么。 :/
【问题讨论】:
-
欢迎来到 Stack Overflow!请不要包含有关问题标题中使用的语言的信息,除非没有它就没有意义。标记用于此目的。
-
也许这个问题是codereview的候选?
标签: c# algorithm recursion generator sudoku