剑指 Offer 29. 顺时针打印矩阵

image.png

遍历,设置边界

执行用时:1 ms, 在所有 Java 提交中击败了97.38% 的用户 内存消耗:39.6 MB, 在所有 Java 提交中击败了73.08% 的用户

  1. class Solution {
  2. public int[] spiralOrder(int[][] matrix) {
  3. if (matrix.length == 0) return new int[0];
  4. // 设置边界
  5. int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;
  6. int index = 0;
  7. int[] res = new int[(right + 1) * (bottom + 1)];
  8. while (true) {
  9. // left to right
  10. for (int i = left; i <= right; i++)
  11. res[index++] = matrix[top][i];
  12. if(++top > bottom) break;
  13. // top to bottom
  14. for (int i = top; i <= bottom; i++)
  15. res[index++] = matrix[i][right];
  16. if (--right < left) break;
  17. // right to left
  18. for (int i = right; i >= left; i--)
  19. res[index++] = matrix[bottom][i];
  20. if (--bottom < top) break;
  21. // bottom to top
  22. for (int i = bottom; i >= top; i--)
  23. res[index++] = matrix[i][left];
  24. if (++left > right) break;
  25. }
  26. return res;
  27. }
  28. }