# 顺时针打印矩阵

# 一、题目描述

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

示例 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]

限制: 0 <= matrix.length <= 100 0 <= matrix[i].length <= 100

# 二、解题思路

将打印一圈拆解为四部,

第一步:从左到右打印一行 第二步:从上到下打印一列 第三步:从右到左打印一行 第四步:从下到上打印一列

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
    if (matrix.length === 0 ) return [];

    let result = [];

    let left = 0;
    let right = matrix[0].length - 1;
    let top = 0;
    let bottom = matrix.length - 1;

    while(true) {
        for (let i = left; i <= right; i++) { result.push(matrix[top][i]); } // left to right
        if(++top > bottom) break;
        for (let i = top; i <= bottom; i++) { result.push(matrix[i][right]); } // top to bottom
        if (--right < left) break;
        for (let i = right; i >= left; i--) { result.push(matrix[bottom][i]); } // right to left
        if (--bottom < top) break;
        for (let i = bottom; i >= top; i--) { result.push(matrix[i][left]); } // bottom to top
        if (++left > right) break;
    }

    return result;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
上次更新: 1/5/2022, 9:25:14 AM