题目描述

题解(按层模拟,边界收缩法)
思路

代码
java
import java.util.ArrayList;
import java.util.List;
class Solution {
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;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while (true) {
// 1. 向右移动:遍历 top 层,从 left 到 right
for (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++; // top 层遍历完,上边界下移
if (top > bottom) break; // 若越界说明全部遍历完了
// 2. 向下移动:遍历 right 列,从 top 到 bottom
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--; // right 列遍历完,右边界左移
if (left > right) break;
// 3. 向左移动:遍历 bottom 层,从 right 到 left
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
bottom--; // bottom 层遍历完,下边界上移
if (top > bottom) break;
// 4. 向上移动:遍历 left 列,从 bottom 到 top
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++; // left 列遍历完,左边界右移
if (left > right) break;
}
return result;
}
}
复杂度分析
- 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。
- 空间复杂度:O(1)。除了输出数组以外,空间复杂度是常数。