【发布时间】:2015-08-20 14:57:14
【问题描述】:
我正在尝试编写具有递归和回溯的数独求解器。但是我的代码存在一些问题,它总是返回 false。我尝试调试,它调用 next(int row, int col) 方法直到第二行第六列,然后它停止并开始回溯。问题是回溯一直持续到我的数独游戏中的第一个单元格,然后它返回 false。它不会将单元格号码替换为其他号码。
这是我的代码...我错过了什么吗?
/** Calls solve for the next cell */
private boolean next(int row, int col) {
if (col < 8)
return solve(row, col + 1);
else
return solve(row + 1, 0);
}
public boolean solve(int row, int col) {
if (row > 8) {
return true;
}
if (model[row][col] != 0) {
if (isSafe(row, col, model[row][col]))
return next(row, col);
}
for (int value = 1; value < 10; value++) {
if (isSafe(row, col, value)) {
model[row][col] = value;
return next(row, col);
}
}
return false;
}
【问题讨论】:
-
你不重置任何地方的值,你怎么能回溯?
标签: java recursion backtracking