题目链接
    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

    示例1:

    1. 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    2. 输出:[1,2,3,6,9,8,7,4,5]

    示例2:

    1. 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
    2. 输出:[1,2,3,4,8,12,11,10,9,5,6,7]

    跟54 类似

    1. class Solution {
    2. public int[] spiralOrder(int[][] matrix) {
    3. if(matrix.length == 0){
    4. return new int[0];
    5. }
    6. int lenY = matrix.length;
    7. int lenX = matrix[0].length;
    8. int num = lenX * lenY;
    9. int count = 0;
    10. // 遍历下标
    11. int i = 0;
    12. int j = 0;
    13. // 循环次数
    14. int loop = Math.min(lenX, lenY) / 2;
    15. int midX = lenX / 2;
    16. int midY = lenY / 2;
    17. // 偏移量
    18. int offsetX = 1;
    19. int offsetY = 1;
    20. // 结果数组
    21. int[] result = new int[num];
    22. while (loop > 0){
    23. // 上
    24. while (j < lenX - offsetX){
    25. result[count] = matrix[i][j];
    26. count++;
    27. j++;
    28. }
    29. // 右
    30. while (i < lenY - offsetY){
    31. result[count] = matrix[i][j];
    32. i++;
    33. count++;
    34. }
    35. // 下
    36. while (j > offsetX - 1){
    37. result[count] = matrix[i][j];
    38. j--;
    39. count++;
    40. }
    41. // 左
    42. while (i > offsetY - 1){
    43. result[count] = matrix[i][j];
    44. i--;
    45. count++;
    46. }
    47. loop--;
    48. offsetX++;
    49. offsetY++;
    50. i++;
    51. j++;
    52. if(count == num){
    53. return result;
    54. }
    55. }
    56. if(lenX < lenY){
    57. for(;i < lenY - Math.min(lenX, lenY) / 2;i++){
    58. result[count] = matrix[i][j];
    59. count++;
    60. }
    61. }
    62. if(lenX > lenY){
    63. for(;j < lenX - Math.min(lenX, lenY) / 2;j++){
    64. result[count] = matrix[i][j];
    65. count++;
    66. }
    67. }
    68. if(lenX == lenY && lenX % 2 != 0){
    69. result[count] = matrix[midX][midY];
    70. }
    71. for (int k = 0;k<num;k++){
    72. System.out.println(result[k]);
    73. }
    74. return result;
    75. }
    76. }