'Logic issue in print spiral matrix logic

I tried to solve the spiral matrix problem, But I am facing some issues with my logic. Code below

const arr = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12]]

function spiralOrderMatrix(arr) {
    let top = 0;
    let left = 0;
    let right = arr[0].length - 1;
    let bottom = arr.length - 1;
    let result = [];
    
    while(top <= bottom && left <= right) {
        for(let i = left; i <= right; i++) {
            result.push(arr[top][i]);
            console.log(arr[top][i], '----top');
        }
        top++;

        for(let j = top; j <= bottom; j++) {
            result.push(arr[j][right]);
            console.log(arr[j][right], '----Right');
        }
        right--;

        for(let k = right; k >= left; k--) {
            result.push(arr[bottom][k]);
            console.log(arr[bottom][k], '----Bottom');
        }
        bottom--;

        for(let l = bottom; l >= top; l--) {
            result.push(arr[l][left]);
            console.log(arr[l][left], '----left');
        }
        left++;
    } 
    console.log(result);
}

spiralOrderMatrix(arr);

 

expected output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]  actual output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6]



Solution 1:[1]

For the bottom and left result push, add if condition to check top is less than equal to the bottom

const arr = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

function spiralOrderMatrix(arr) {
    let top = 0;
    let left = 0;
    let right = arr[0].length - 1;
    let bottom = arr.length - 1;
    let result = [];

    while (top <= bottom && left <= right) {
        for (let i = left; i <= right; i++) {
            result.push(arr[top][i]);
            console.log(arr[top][i], '----top');
        }
        top++;

        for (let j = top; j <= bottom; j++) {
            result.push(arr[j][right]);
            console.log(arr[j][right], '----Right');
        }
        right--;
        if (top <= bottom) {
            for (let k = right; k >= left; k--) {
                result.push(arr[bottom][k]);
                console.log(arr[bottom][k], '----Bottom');
            }
        }
        bottom--;
        if (top <= bottom) {
            for (let l = bottom; l >= top; l--) {
                result.push(arr[l][left]);
                console.log(arr[l][left], '----left');
            }
        }
        left++;
    }
    console.log(result);
}

spiralOrderMatrix(arr);

Ref:https://gist.github.com/lienista/af013a6425eaf781cbc659474f0b91b6

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1