import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
// 初始化
ArrayList<Integer> res = new ArrayList<>();
// 预处理
if (matrix.length == 0) return res;
if (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 < (matrix.length+1)/2 && left < (matrix[0].length+1)/2 ) {
// 输出上边 左到右
for (int i = left; i <= right; i++) {
res.add(matrix[top][i]);
}
// 输出右边 上到下
for (int i = top+1; i <= bottom; i++) {
res.add(matrix[i][right]);
}
// 输出下边 右到左
for (int i = right-1; bottom != top && left <= i; i--) {
res.add(matrix[bottom][i]);
}
// 输出左边 下到上
for (int i = bottom-1; left != right && top+1 <= i; i--) {
res.add(matrix[i][left]);
}
// 遍历完一圈后,更新边界值,都往里面靠1格
top++;
right--;
bottom--;
left++;
}
// 矩阵遍历结束,输出结果
return res;
}
}