为了好玩,我决定将可以在此plunkr上找到的代码从Matlab移植到Javascript。
var propagate = function(depth, board, counter) {
console.log("Current state >> depth:", depth, " board: ", board, " counter: ", counter);
var validSolution = checkSolution(board);
if ((depth == board.length + 1) && (validSolution)) {
counter = counter + 1;
console.log("Found solution [", counter, "] ", board);
};
if (depth <= board.length) {
for (var i = 1; i <= board.length; i++) {
if (!(board.indexOf(i) > -1)) {
board[depth-1] = i;
propagate(depth + 1, board, counter);
};
};
};
};
在达到最终深度水平之后,我希望它能够继续前一个水平。相反,它只是停止。
为什么?
答案 0 :(得分:2)
当您将数组作为参数发送时,您将无法获得该数组的新副本,但它仍然是相同的数组对象。这意味着当你回来时董事会不会改变。
您可以存储您更改的项目的先前值,以便您可以在通话后更改电路板:
if (!(board.indexOf(i) > -1)) {
var prev = board[depth-1];
board[depth-1] = i;
propagate(depth + 1, board, counter);
board[depth-1] = prev;
}