import java.util.*;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(matrix.length == 0){
return res;
}
//1. 设定边界
int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
//2. 循环遍历
while(true){
//2.1 遍历第一行
for(int i = left; i <= right; ++i){
res.add(matrix[top][i]);
}
//2.2 调整上边界
if (++top > bottom) {
break;
}
//2.3 遍历最后一列
for(int i = top; i <= bottom; ++i){
res.add(matrix[i][right]);
}
//2.4 调整右边界
if (--right < left) {
break;
}
//2.5 遍历最后一行
for(int i = right; i >= left; --i){
res.add(matrix[bottom][i]);
}
//2.6 调整下边界
if (--bottom < top) {
break;
}
//2.7 遍历第一列
for(int i = bottom; i >= top; --i){
res.add(matrix[i][left]);
}
//2.8 调整左边界
if (++left > right) {
break;
}
}
return res;
}
}