c# - 为什么我在数独求解器 C# 中不断收到 Stackoverflow 错误
问题描述
编辑:我真的很抱歉。我的错误在那里
//get unassigned position
unassignedPos = GetNextUnassignedValue(matrix);
int col = unassignedPos.Item1;
int row = unassignedPos.Item2;
row 必须是 item1,col 必须是 item2... 还发现我尝试了无法正确解决的数独。
我是 C# 新手,刚开始更深入地编码。有谁知道为什么我在以下代码示例中不断收到 Stackoverflow 错误?我仔细检查并重新排列了约束,它们应该没问题。
class SudokuCalc
{
(int, int) finish = (9, 9);
(int, int) unassignedPos = (0, 0);
//method to recursively solve the sudoku
public bool Solve(int[,] matrix)
{
//if we are at the finish position return true
if (finish.Item1 == GetNextUnassignedValue(matrix).Item1
&& finish.Item2 == GetNextUnassignedValue(matrix).Item2)
{
return true;
}
//get unassigned position
unassignedPos = GetNextUnassignedValue(matrix);
int col = unassignedPos.Item1;
int row = unassignedPos.Item2;
//go through all possible values
for (int value = 1; value <= 9; value++)
{
if (IsValid(matrix, row, col, value))
{
matrix[row, col] = value;
//recursively try to solve
if (Solve(matrix))
{
return true;
}
// if we couldnt solve the sudoku
// set the previous value 0 and try again
matrix[row, col] = 0;
}
}
return false;
}
解决方案
在当前情况下,StackOverflow 异常意味着您的Solve
方法以递归方式调用自身的次数过多。发生这种情况时,您可以停止调试器并查看包含大量嵌套Solve
调用的所有堆栈跟踪。
在您的条件下,您有一些极端情况会强制代码Solve
无限调用方法。要跟踪您可以在Solve
方法的开头添加日志记录并写入调用您的磁盘矩阵。可能在某个时候,您会一遍又一遍地获得相同的价值。
推荐阅读
- ios - 未找到虚拟设备 - Ionic Cordova Emulate iOS
- javascript - 使用带有 HTML 类的 CSS 和 JavaScript 更改多个段落的字体大小。
- java - firebase 存储的 getDownloadUrl() 为所有上传的文件返回相同且错误的链接。如何解决这个问题?
- python - 在条件语句中检查对象类型的正确方法是什么 - python
- docker - VS2017 构建失败 - DOCKER_REGISTRY
- css - 移动媒体查询不起作用
- android - 离开活动后禁用 CountDownTimer
- elasticsearch - 否定的“LIKE”或“CONTAINS”语句的 Elasticsearch 等效项是什么?
- visual-studio - 视觉工作室有“自动完成”扩展吗?
- apache-kafka - 尝试运行 Kafka JDBC 源连接器时出现 CORRUPT_MESSAGE