核心思路
-
定义四个边界:上、下、左、右
-
按 右 → 下 → 左 → 上 顺序遍历
-
每遍历完一条边,就把对应边界往内缩一圈
-
直到边界重合,遍历结束
关键判断
- 遍历下排 前要判断:
top <= bottom - 遍历左列 前要判断:
left <= right防止单行 / 单列时重复遍历
四个方向(固定顺序)
- 上排:左 → 右
- 右列:上 → 下
- 下排:右 → 左
- 左列:下 → 上 走完一轮,边界全部往里缩一圈。
完整代码实现:
java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
// 判空
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return res;
}
// 定义四个边界
int top = 0; // 上边界
int bottom = matrix.length - 1; // 下边界
int left = 0; // 左边界
int right = matrix[0].length - 1; // 右边界
// 一直转圈,直到边界越界
while (top <= bottom && left <= right) {
// 1. 从左到右遍历上边界
for (int j = left; j <= right; j++) {
res.add(matrix[top][j]);
}
top++; // 上边界用完,向下缩
// 2. 从上到下遍历右边界
for (int i = top; i <= bottom; i++) {
res.add(matrix[i][right]);
}
right--; // 右边界用完,向左缩
// 3. 从右到左遍历下边界(要判断还有没有剩余行)
if (top <= bottom) {
for (int j = right; j >= left; j--) {
res.add(matrix[bottom][j]);
}
bottom--; // 下边界用完,向上缩
}
// 4. 从下到上遍历左边界(要判断还有没有剩余列)
if (left <= right) {
for (int i = bottom; i >= top; i--) {
res.add(matrix[i][left]);
}
left++; // 左边界用完,向右缩
}
}
return res;
}
}