public ArrayList<Integer>spiralOrder(int[][] matrix){
ArrayList<Integer> res =newArrayList<>();if(matrix.length ==0)return res;int top =0, bottom = matrix.length -1;int left =0, right = matrix[0].length -1;int i;// 循环打印的结束条件while(top <= bottom && left <= right){// 上面 从左到右for(i = left; i <= right; i++)
res.add(matrix[top][i]);// 右边 从上到下for(i = top +1; i <= bottom; i++)
res.add(matrix[i][right]);// 下面 从右到左, top != bottom 当只有一行时避免和上面重复// 注意边界,i 从 right - 1 开始for(i = right -1; top != bottom && i >= left; i--)
res.add(matrix[bottom][i]);// 左边 从下到上, left != right 当只有一列时避免和右边重复// 注意边界,i 从 bottom - 1 到 top + 1 (不是 top - 1)for(i = bottom -1; left != right && i >= top +1; i--)
res.add(matrix[i][left]);
top++;
bottom--;
left++;
right--;}return res;}