Files
LeetCode/矩阵/2. 螺旋矩阵.md
T
2025-10-02 22:14:32 +08:00

83 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 螺旋矩阵
## 题目
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 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]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
## 思路
- 模拟
- 方向
- →↓←↑
- 边界
- `up`
- `down`
- `left`
- `right`
## 代码
```java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
// Init: up, down, left, right
int up = 0;
int down = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
// Init: ans
List<Integer> ans = new ArrayList<>();
int tar = matrix.length * matrix[0].length;
// Traverse
while (left <= right && up <= down) {
for (int i = left; i <= right; i++) {
ans.add(matrix[up][i]);
}
up ++;
for (int i = up; i <= down; i++) {
ans.add(matrix[i][right]);
}
right --;
if (up <= down) {
for (int i = right; i >= left; i--) {
ans.add(matrix[down][i]);
}
}
down --;
if (left <= right) {
for (int i = down; i >= up; i--) {
ans.add(matrix[i][left]);
}
}
left ++;
}
return ans;
}
}
```