位置 帝国网站管理系统>职场>笔试面试>LeetCode

54.螺旋矩阵

54.螺旋矩阵
54.螺旋矩阵
54.螺旋矩阵
54.螺旋矩阵

54. 螺旋矩阵

2024 年 11 月 20 日这天,鲁迅定下了一个小目标,接下来连续更新 46 天,把

LeetCode 100 搞定,下面开始更新 Spring Boot 的教程,结合技术派一起来。今

天先搞定 054.螺旋矩阵。

题意

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

难度

中等

示例

示例 1:

054.螺旋矩阵-20241120170746.png

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

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

示例 2:

054.螺旋矩阵-20241120170805.png

输入: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]

分析

按照螺旋顺序,可以看成一圈一圈地剥开矩阵:

• 从左到右(遍历当前上边界)。

• 从上到下(遍历当前右边界)。

• 从右到左(遍历当前下边界)。

• 从下到上(遍历当前左边界)。

每遍历完一圈,就需要缩小边界,直到所有元素都被遍历。

我们可以用 4 个变量 top, bottom, left, right 来分别表示上下左右的边界。

每次遍历一圈后,更新这些边界,直到 top > bottom 或 left > right。

class Solution05401 {

public List<Integer> spiralOrder(int[][] matrix) {

List<Integer> result = new ArrayList<>();

if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {

return result;

}

int top = 0, bottom = matrix.length - 1; // 上下边界

int left = 0, right = matrix[0].length - 1; // 左右边界

while (top <= bottom && left <= right) {

// 从左到右遍历当前上边界

for (int i = left; i <= right; i++) {

result.add(matrix[top][i]);

}

top++; // 上边界缩小

// 从上到下遍历当前右边界

for (int i = top; i <= bottom; i++) {

result.add(matrix[i][right]);

}

right--; // 右边界缩小

// 从右到左遍历当前下边界(需要检查上下边界是否相交)

if (top <= bottom) {

for (int i = right; i >= left; i--) {

result.add(matrix[bottom][i]);

}

bottom--; // 下边界缩小

}

// 从下到上遍历当前左边界(需要检查左右边界是否相交)

if (left <= right) {

for (int i = bottom; i >= top; i--) {

result.add(matrix[i][left]);

}

left++; // 左边界缩小

}

}

return result;

}

public static void main(String[] args) {

Solution05401 solution = new Solution05401();

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

System.out.println(solution.spiralOrder(matrix)); // 输出: [1, 2, 3, 6, 9, 8, 7, 4,

5]

}

}

①、从左到右:遍历当前 top 行的 [left, right] 范围,添加元素后,top++。

②、从上到下:遍历当前 right 列的 [top, bottom] 范围,添加元素后,right–。

③、从右到左:如果 top <= bottom,遍历当前 bottom 行的 [right, left] 范围,添加元

素后,bottom–。

④、从下到上:如果 left <= right,遍历当前 left 列的 [bottom, top] 范围,添加元素

后,left++。

很好理解,来看一下题解效率:

054.螺旋矩阵-20241120172114.png

总结

本题其实并不比简单题难多少,或者说,其实就是让你抓住 顺时针旋转 这个关键点,再

依次缩小边界便可以解题了。

力扣链接:https://leetcode.cn/problems/spiral-matrix/