gpt4 book ai didi

javascript - 如何更改矩阵中的单个元素?

转载 作者:行者123 更新时间:2023-12-02 23:17:15 24 4
gpt4 key购买 nike

我正在尝试解决“螺旋矩阵”算法问题。我试图通过创建一个跟踪我已经去过的位置的引用矩阵 [refMatrix] 和两个跟踪我当前在矩阵中的位置的指针来解决这个问题。

当我尝试将引用矩阵中的值从 T 切换到 F 时,它不是只切换该元素,而是切换整个列。我不明白为什么。

const spiralOrder = function(matrix) {

const spiralArray = [];
const h = matrix.length;
const l = matrix[0].length;
const refMatrix = new Array(h)
refMatrix.fill(new Array(l).fill(true));

let y = 0;
let x = 0;
let direction = 'right';

const movePointers = () => {
if(direction === 'right'){
x++;
}else if(direction === 'down'){
y++;
}else if(direction === 'left'){
x--;
}else if(direction === 'up'){
y--;
}
};

const changeDirection = () => {
if(direction === 'right'){
x--;
y++;
direction = 'down';
}else if(direction === 'down'){
y--;
x--;
direction = 'left'
}else if(direction === 'left'){
x++;
y--;
direction = 'up';
}else if(direction === 'up'){
y++;
x++;
direction = 'right';
}
};

for(let i = 0; i < (h * l); i ++){
console.log(refMatrix); //<=========== CONSOLE LOG HERE
if(y > h || x > l || x < 0 || y < 0){
changeDirection();
}else if(!refMatrix[y][x]){
changeDirection();
}else if(refMatrix[y][x]){
spiralArray.push(matrix[y][x]);
refMatrix[y][x] = false; //<====== REF ELEMENT CHANGE HERE
movePointers();
}
}

return spiralArray;
};

在我的注释所指示的行中,它应该只更改矩阵中的一个元素,而不是整个列。

我在 for 循环的开头包含了一个 console.log,以显示 refMatrix 如何在每次迭代中发生变化。

编辑:如果我将引用矩阵更改为硬编码的“真实”矩阵,问题就会消失。但这不允许我解决不同输入的问题。

 const refMatrix = [
[true, true, true, true],
[true, true, true, true],
[true, true, true, true]
]

最佳答案

当我构建引用矩阵时,每个元素都指向同一个数组。当我更改数组中的一个点时,由于所有“行”都指向同一个数组,因此它更改了所有行。

新的“refArray”构造:

 for(let i = 0; i < h; i ++){
refMatrix.push(new Array(l).fill(true));
}

关于javascript - 如何更改矩阵中的单个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57121042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com