左到右 结束时 ++top>bottom 迭代终止
上到下 结束时 --right<left 迭代终止
右到左 结束时 top>--bottom 迭代终止
下到上 结束时 ++left>right 迭代终止
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
int len = matrix.length;
if (matrix == null || len == 0){
return res;
}
int left = 0;
int right = matrix[0].length-1;
int top = 0;
int bottom = matrix.length-1;
while (true){
for (int i = left; i <=right ; i++) {
int val = matrix[top][i];
res.add(val);
}
if (++top>bottom) break;
for (int i = top; i <=bottom ; i++) {
int val = matrix[i][right];
res.add(val);
}
if (--right<left)break;
for (int i = right; i >=left ; i--) {
int val = matrix[bottom][i];
res.add(val);
}
if (top>--bottom) break;
for (int i = bottom; i >=top ; i--) {
int val = matrix[i][left];
res.add(val);
}
if (++left>right) break;
}
return res;
}
}