categories:[Blog,算法]


54. 螺旋矩阵

难度中等
给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:
54. 螺旋矩阵 - 图1
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:
54. 螺旋矩阵 - 图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]

  1. class Solution {
  2. public List<Integer> spiralOrder(int[][] matrix) {
  3. List<Integer> order = new ArrayList<Integer>();
  4. if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
  5. return order;
  6. }
  7. int rows = matrix.length, columns = matrix[0].length;
  8. int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
  9. while (left <= right && top <= bottom) {
  10. for (int column = left; column <= right; column++) {
  11. order.add(matrix[top][column]);
  12. }
  13. for (int row = top + 1; row <= bottom; row++) {
  14. order.add(matrix[row][right]);
  15. }
  16. if (left < right && top < bottom) {//不加一行的时候有重复问题
  17. for (int column = right - 1; column > left; column--) {
  18. order.add(matrix[bottom][column]);
  19. }
  20. for (int row = bottom; row > top; row--) {
  21. order.add(matrix[row][left]);
  22. }
  23. }
  24. left++;
  25. right--;
  26. top++;
  27. bottom--;
  28. }
  29. return order;
  30. }
  31. // 作者:LeetCode-Solution
  32. // 链接:https://leetcode-cn.com/problems/spiral-matrix/solution/luo-xuan-ju-zhen-by-leetcode-solution/
  33. // 来源:力扣(LeetCode)
  34. // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  35. }

解析image.png