算法:顺时针遍历矩阵 螺旋矩阵转换为顺时针列表spiral matrix

题目

54. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

解决

按照顺时针遍历螺旋矩阵,只要定义好上下左右四条边,按照顺序遍历就好。
注意:需要避免重复填值的情况,条件要同时判断left <= right && top <= down.
算法:顺时针遍历矩阵 螺旋矩阵转换为顺时针列表spiral matrix_第1张图片

class Solution {
     
    public List<Integer> spiralOrder(int[][] matrix) {
     
        List<Integer> list = new ArrayList<>();

    // check edge
    if (matrix == null || matrix.length == 0) {
     
      return list;
    }

    int top = 0;
    int down = matrix.length - 1;
    int left = 0;
    int right = matrix[0].length - 1;

    while (top <= down && left <= right) {
     

      // top
      for (int i = left; i <= right  && top <= down; i++) {
     
        list.add(matrix[top][i]);
      }
      top++;

      // right
      for (int i = top; i <= down && left <= right; i++) {
     
        list.add(matrix[i][right]);
      }
      right--;

      // down
      for (int i = right; i >= left && top <= down; i--) {
     
        list.add(matrix[down][i]);
      }
      down--;

      // left
      for (int i = down; i >= top && left <= right; i--) {
     
        list.add(matrix[i][left]);
      }
      left++;
    }

    return list;
    }
}

你可能感兴趣的:(算法,Array,Spiral,matrix,矩阵,顺时针遍历矩阵)