我正在分析暴力算法,并有一个问题。
var solveSudoku = function (grid, row, col) {
var field = findUnassignedLocation(grid, row, col);
row = field[0];
col = field[1];
if (row === -1) {
if (!newGameStatus) fillTheDom(grid);
return true;
}
for (var num = 1; num <= 9; num++) {
if (newGameStatus) {
num = Math.floor(Math.random() * 9) + 1;
}
if (isValid(grid, row, col, num)) {
console.log(row + ' ' + col)
grid[row][col] = num;
if (solveSudoku(grid, row, col)) {
return true;
}
console.log(row + ' ' + col)
grid[row][col] = 0;
}
}
return false;
}
var findUnassignedLocation = function (grid, row, col) {
var foundZero = false;
var location = [-1, -1];
while (!foundZero) {
if (row === 9) {
foundZero = true;
} else {
if (grid[row][col] === 0) {
location[0] = row;
location[1] = col;
foundZero = true;
} else {
if (col < 8) {
col++;
} else {
row++;
col = 0;
}
}
}
}
return location;
}
如果没有要填充的数字(每个数字都无效),递归函数返回false,对吗?然后以某种方式重置先前填充的单元格。它如何回到最后一个单元格?
答案 0 :(得分:0)
每次调用一个函数时,其状态都会被保存(直到所有以下状态都失败),如果它们失败,处理器会跳回到最后一个分支,该分支至少有一个尚未失败的状态要继续,直到解决方案为止被发现或一切都失败了。
我可以制作一个gif,尽可能简单地解释它,但我只能在工作后这样做
答案 1 :(得分:0)
想象一下递归就像格式化一样。
solveSudoku(firstCell)
# Context : Global
On the first cell :
From 1 to 9 :
Is 1 valid ?
Yes.
If solveSudoku(nextCell):
# Context : We're in the loop of the first cell at iteration 1.
On the second cell :
From 1 to 9 :
Is 1 valid ?
No.
Is 2 valid ?
Yes.
If solveSudoku(nextCell):
# Context : We're in the loop of the second cell at iteration 2 which is in the loop of the first cell at iteration 1.
On the third cell :
From 1 to 9 :
Is 1 valid ?
No.
Is 2 valid ?
No.
Is 3 valid ?
No.
...
Is 9 valid ?
No.
Return false.
solveSudoku(nextCell = thirdCell) returned false, going on the loop. <<<<<<<<< This is "How does it goes back to the last cell?"
# Context : We're in the loop of the first cell at iteration 1.
Is 3 valid ?
Yes.
If solveSudoku(nextCell):
# Context : We're in the loop of the second cell at iteration 3 which is in the loop of the first cell at iteration 1.
On the third cell :
From 1 to 9 :
Is 1 valid ?
No.
Is 2 valid ?
Yes. <<<<<<< 2 is now valid and we can go on !
If solveSudoku(nextCell):
# Context : We're in the loop of the third cell at iteration 2 which is in the loop of the second cell at iteration 3 which is in the loop of the first cell at iteration 1.
On the fourth cell...
正如您所看到的,递归更深入,可以简单地逃避一个深度级别来尝试另一条路径。