[54] 螺旋矩阵 js

题目描述:给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]

* 输出:[1,2,3,6,9,8,7,4,5]

解题思路:

按照顺时针一行一列,往里收缩

解法一:

function spiralOrder(matrix) {
    let left = 0;
    let right = matrix[0].length - 1;
    let top = 0;
    let bottom = matrix.length - 1 ;
    let res = [];


   // 按照顺时针进行输出,规定好收缩边界
    while (left <= right && top <= bottom) {
        // 第一行
        for (let i = left; i <= right; i++) {
            res.push(matrix[top][i]);
        };
        top++;
        // 最后一列
        for (let i = top; i <= bottom; i++) {
            res.push(matrix[i][right]);
        };
        right--;
        // 最后一行

        if (top <= bottom && left <= right) {
            for (let i = right; i >= left; i--) {
                res.push(matrix[bottom][i]);
            }
            bottom--;

            // 第一列
            for (let i = bottom; i >= top; i--) {
                res.push(matrix[i][left]);
            }
            left++;
        }
        
    }
    return res;

    
};

用时:

// Your runtime beats 30.54 % of typescript submissions
    // Your memory usage beats 84.1 % of typescript submissions (42.1 MB)

你可能感兴趣的:(leetcode,矩阵,算法,leetcode,javascript)