刷题19 螺旋矩阵

42 阅读1分钟

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

 

示例 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]

 

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

题解:

   class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
     //  数学方式计算
    int bottom=matrix.length-1,right=matrix[0].length-1;
    List<Integer> result=new ArrayList<>();
    int top=0,left=0;
    int step=0;
    while(top<=bottom&&left<=right){
        step++;
        if(step%4==1){//右走
            for(int i=left;i<=right;i++){
                result.add(matrix[top][i]);
            }
            top++;
        }else if(step%4==2){//下走
          for(int i=top;i<=bottom;i++){
                result.add(matrix[i][right]);
            }
            right--;

        }else if(step%4==3){//左走
             for(int i=right;i>=left;i--){
                result.add(matrix[bottom][i]);
            }
            bottom--;
        }else if(step%4==0){//上走
         for(int i=bottom;i>=top;i--){
                result.add(matrix[i][left]);
            }
            left++;
        }

    }
    return result;
}

}