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

题目描述

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

image-20250510231223304

image-20250510231242071

image-20241107205533289

思路分析

这个问题可以通过模拟顺时针的打印过程来实现。

参考代码

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
// spiralOrder
func spiralArray(matrix [][]int) []int {
	var res []int
	if len(matrix) == 0 {
		return res
	}

	top, bottom := 0, len(matrix)-1
	left, right := 0, len(matrix[0])-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
}

➡️ 点击查看 Java 题解

1
write your code here

相似题目

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