题目

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

示例 1:

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

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

限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

解题思路

1、辅助矩阵法

可以模拟打印矩阵的路径。初始位置是矩阵的左上角,初始方向是向右,当路径超出界限或者进入之前访问过的位置时,顺时针旋转,进入下一个方向。

判断路径是否进入之前访问过的位置需要使用一个与输入矩阵大小相同的辅助矩阵 visited,其中的每个元素表示该位置是否被访问过。当一个元素被访问时,将 visited 中的对应位置的元素设为已访问。

如何判断路径是否结束?由于矩阵中的每个元素都被访问一次,因此路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时即为完整路径,将该路径返回。

复杂度分析

  • 时间复杂度:O(mn),其中 m 和 n 分别是输入矩阵的行数和列数。矩阵中的每个元素都要被访问一次。
  • 空间复杂度:O(mn)。需要创建一个大小为 m×n 的矩阵 visited 记录每个位置是否被访问过。

2、按层模拟法

image.png
image.png

实现

1、辅助矩阵法

  1. class Solution {
  2. public int[] spiralOrder(int[][] matrix) {
  3. if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  4. return new int[0];
  5. }
  6. int rows = matrix.length, columns = matrix[0].length;
  7. boolean[][] visited = new boolean[rows][columns];
  8. int total = rows * columns;
  9. int[] result = new int[total];
  10. int row = 0, column = 0;
  11. int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
  12. int directionIndex = 0;
  13. for (int i = 0; i < total; i++) {
  14. result[i] = matrix[row][column];
  15. visited[row][column] = true;
  16. int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
  17. if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
  18. directionIndex = (directionIndex + 1) % 4;
  19. }
  20. row += directions[directionIndex][0];
  21. column += directions[directionIndex][1];
  22. }
  23. return result;
  24. }
  25. }

image.png

2、按层模拟法

  1. class Solution {
  2. public int[] spiralOrder(int[][] matrix) {
  3. if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  4. return new int[0];
  5. }
  6. int rows = matrix.length, columns = matrix[0].length;
  7. int[] result = new int[rows * columns];
  8. int index = 0;
  9. int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
  10. while (left <= right && top <= bottom) {
  11. for (int column = left; column <= right; column++) {
  12. result[index++] = matrix[top][column];
  13. }
  14. for (int row = top + 1; row <= bottom; row++) {
  15. result[index++] = matrix[row][right];
  16. }
  17. if (left < right && top < bottom) {
  18. for (int column = right - 1; column > left; column--) {
  19. result[index++] = matrix[bottom][column];
  20. }
  21. for (int row = bottom; row > top; row--) {
  22. result[index++] = matrix[row][left];
  23. }
  24. }
  25. left++;
  26. right--;
  27. top++;
  28. bottom--;
  29. }
  30. return result;
  31. }
  32. }

image.png