LeetCode 54. 螺旋矩阵

题目描述

54. 螺旋矩阵

image-20230304214740996

image-20230304214747567

思路分析

螺旋矩阵是一个经典的模拟题,需要按照顺时针的方向从外到内逐层遍历矩阵。

image-20250506231256592

参考代码

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
func spiralOrder(matrix [][]int) []int {
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return nil
	}

	m, n := len(matrix), len(matrix[0])
	res := make([]int, 0, m*n)
	top, bottom, left, right := 0, m-1, 0, n-1

	for top <= bottom && left <= right {
		// 从左到右遍历 top 行
		for i := left; i <= right; i++ {
			res = append(res, matrix[top][i])
		}
		top++

		// 从上到下遍历 right 列
		for i := top; i <= bottom; i++ {
			res = append(res, matrix[i][right])
		}
		right--

		// 判断是否还有行可遍历
		if top <= bottom {
			// 从右到左遍历 bottom 行
			for i := right; i >= left; i-- {
				res = append(res, matrix[bottom][i])
			}
			bottom--
		}

		// 判断是否还有列可遍历
		if left <= right {
			// 从下到上遍历 left 列
			for i := bottom; i >= top; i-- {
				res = append(res, matrix[i][left])
			}
			left++
		}
	}

	return res
}
  • 时间复杂度:O(m * n),我们需要遍历矩阵中的每一个元素一次。
  • 空间复杂度:O(m * n),用于存储返回的结果数组。

➡️ 点击查看 Java 题解

1
write your code here

image-20250506231546886

本文作者:
本文链接: https://hgnulb.github.io/blog/2025/76110162
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!