mengjian-github/leetcode

剑指 Offer 29. 顺时针打印矩阵

Opened this issue · 1 comments

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

 

示例 1:

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

和之前回形的题一模一样,这次采用层次遍历,比较难搞的是边界判断:

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
    let top = 0;
    let bottom = matrix.length;
    let left = 0;
    let right = matrix[0]?.length || 0;
    const result = [];

    while (top < bottom && left < right) {
        // 打印top
        for (let i = left; i < right; i++) {
            result.push(matrix[top][i]);
        }
        // 打印right
        for (let i = top + 1; i < bottom; i++) {
            result.push(matrix[i][right - 1]);
        }

        if (top < bottom - 1) {
            // 打印bottom
            for (let i = right - 2; i >= left; i--) {
                result.push(matrix[bottom - 1][i]);
            }
        }

        if (left < right - 1) {
            // 打印left
            for (let i = bottom - 2; i > top; i--) {
                result.push(matrix[i][left]);
            }
        }
        
        
        // 向内缩减一圈
        top++;
        left++;
        right--;
        bottom--;
    }

    return result;
};