在 JavaScript 中将数组推入另一个数组时,数组会返回起始值

问题描述 投票:0回答:1

我有这个简单的递归

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 ]
  ]

这是矩阵的起始值。 ¿为什么会发生这种情况?

javascript arrays variables recursion
1个回答
0
投票

正如评论中所述,解决方案是将矩阵实际复制到解决方案中,而不是直接引用它。

    if (!nextEmpty) {
    let copy = matrix.map((row) => row.slice());
    solutions.push(copy);
}
© www.soinside.com 2019 - 2024. All rights reserved.