import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
if(matrix == null || matrix.length == 0){
return res;
}
int m = matrix.length;
int n = matrix[0].length;
int startX = 0;
int startY = 0;
int endX = m - 1 - startX;
int endY = n - 1 - startY;
// 必须两个条件都满足
while(2 * startX < m && 2 * startY < n){
endX = m - 1 - startX;
endY = n - 1 - startY;
//打印上边界(从左往右)
for(int j = startY; j <= endY; j++){
res.add(matrix[startX][j]);
}
//打印右边界(从上往下,至少两行)
if(endX > startX){
for(int i = startX + 1; i <= endX; i++){
res.add(matrix[i][endY]);
}
}
//打印下边界(至少两行两列)
if(endX > startX && endY > startY){
for(int j = endY - 1; j >= startY; j--){
res.add(matrix[endX][j]);
}
}
//打印左边界(至少三行两列) (注意:不是两行三列)
if(endX - 1 > startX && endY > startY){
for(int i = endX - 1; i > startX; i--){
res.add(matrix[i][startY]);
}
}
//两个都要++,不能只加一个
startX ++;
startY ++;
}
return res;
}
}