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

时间:2019-07-20 01:09:43

标签: javascript matrix

我正在尝试解决“螺旋矩阵”算法问题。我正在尝试通过创建一个引用矩阵[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在每次迭代中如何变化。

编辑:如果我将参考矩阵更改为硬编码的“ true”,则问题就消失了。但这不允许我解决各种输入问题。

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

1 个答案:

答案 0 :(得分:1)

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

新的“ refArray”结构:

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