题目

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

思路

image.png
按照这个图片的思路 先
从左—->右,
从上—->下,
从右—->左,
从下—->上
同时要注意收缩边界

代码

  1. public int[] spiralOrder(int[][] matrix) {
  2. if(matrix.length == 0) return new int[0];
  3. int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1, x = 0;
  4. int[] res = new int[(right + 1) * (bottom + 1)];
  5. while(true) {
  6. for(int i = left; i <= right; i++) res[x++] = matrix[top][i]; // left to right.
  7. //每次循环top都加一,如果top比bottom大说明已经遍历完成
  8. if(++top > bottom) break;
  9. for(int i = top; i <= bottom; i++) res[x++] = matrix[i][right]; // top to bottom.
  10. //因为是向内遍历,所以每次right都减1
  11. if(left > --right) break;
  12. for(int i = right; i >= left; i--) res[x++] = matrix[bottom][i]; // right to left.
  13. if(top > --bottom) break;
  14. for(int i = bottom; i >= top; i--) res[x++] = matrix[i][left]; // bottom to top.
  15. if(++left > right) break;
  16. }
  17. return res;
  18. }