解题思路(边界模拟法)
我们可以通过维护四个边界(上、下、左、右)来模拟顺时针螺旋遍历的过程:
- 从左到右遍历当前上边界的行,然后上边界向下移动。
- 从上到下遍历当前右边界的列,然后右边界向左移动。
- 如果上下边界仍有未遍历的行,则从右到左遍历当前下边界的行,然后下边界向上移动。
- 如果左右边界仍有未遍历的列,则从下到上遍历当前左边界的列,然后左边界向右移动。
- 重复以上步骤,直到所有边界交叉,遍历结束。

Java 代码实现
import java.util.*;
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix == null || matrix.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. 从左到右遍历上边界
( left; j <= right; j++) {
res.add(matrix[top][j]);
}
top++;
( top; i <= bottom; i++) {
res.add(matrix[i][right]);
}
right--;
(top <= bottom) {
( right; j >= left; j--) {
res.add(matrix[bottom][j]);
}
bottom--;
}
(left <= right) {
( bottom; i >= top; i--) {
res.add(matrix[i][left]);
}
left++;
}
}
res;
}
}




