提问人:Luis Belloch 提问时间:10/28/2023 更新时间:10/28/2023 访问量:37
在 JavaScript 中推送到另一个数组时,数组返回起始值 [duplicate]
Array returns to starting values when pushed into another array in JavaScript [duplicate]
问:
我有这个简单的递归
function solve(matrix, pieces) {
// Get next -1
let nextEmpty = getNextEmtpy(matrix);
if (!nextEmpty) {
console.log(matrix)
solutions.push(matrix);
}
let row = nextEmpty.row;
let col = nextEmpty.col;
// Try all pieces that are not in the matrix
for (let i = 1; i < pieces.length; i++) {
if (matrix.flat().includes(i)) continue;
for (let r = 0; r < 4; r++) {
let fit = rotatePiece(pieces[i]);
if (col == 0) {
if (fit[0] != 0) continue;
}
if (row == 0) {
if (fit[1] != 0) continue;
}
if (col == matrix[0].length - 1) {
if (fit[2] != 0) continue;
}
if (row == matrix.length - 1) {
if (fit[3] != 0) continue;
}
// If the piece is not in a border
if (col > 0) {
if (fit[0] != pieces[matrix[row][col - 1]][2]) continue;
}
if (row > 0) {
if (fit[1] != pieces[matrix[row - 1][col]][3]) continue;
}
// Add the piece to the matrix
matrix[row][col] = i;
// Update pieces
pieces[i] = fit;
// Recurse
let solution = solve(matrix, pieces);
// Reset the value
matrix[row][col] = -1;
}
}
return false;
}
它应该打印相同的值并将其添加到变量解决方案中。但是,它可以正确打印:
[
[ 25, 1, 17, 24, 7 ],
[ 19, 16, 23, 8, 15 ],
[ 12, 14, 4, 2, 21 ],
[ 5, 9, 11, 6, 18 ],
[ 10, 13, 22, 20, 3 ]
]
但是当将这个矩阵添加到解决方案中时,即 [],它添加了:
[
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ],
[ -1, -1, -1, -1, -1 ]
]
这是矩阵的起始值。 ¿为什么会发生这种情况?
答:
-1赞
Luis Belloch
10/28/2023
#1
正如评论中所说,解决方案实际上是将矩阵复制到解决方案中,而不是直接引用它。
if (!nextEmpty) {
let copy = matrix.map((row) => row.slice());
solutions.push(copy);
}
评论