LeetCode 高级 - 螺旋矩阵

螺旋矩阵

给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

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

示例 2:

输入:
[
  [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, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
  • 环数为3/2=1(从0开始计数,方便坐标变换)。

第0环的输出顺序:
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]

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

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

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

这样,避免了四角上重复输出。

代码

    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res = new ArrayList<>();
            if(matrix == null || matrix.length ==0){
                return res;
            }
            int numi = matrix.length;
            int numj = matrix[0].length;
            //环数
            int loop = numi>numj?(numj+1)/2:(numi+1)/2;

            for(int i=0;i<loop;i++,numi-=2,numj-=2){

                for(int col = i;col<i+numj;col++){
                    res.add(matrix[i][col]);
                }
                for(int row = i+1;row<i+numi;row++){
                    res.add(matrix[row][i+numj-1]);
                }
                //最后一环为一行或一列,则在上面两步之后已经全部输出,直接退出即可
                if(numi ==1||numj==1)
                    break;

                for(int col = i+numj-2;col>=i;col--){
                    res.add(matrix[i+numi-1][col]);
                }
                for(int row = i+numi -2;row>i;row--){
                    res.add(matrix[row][i]);
                }
            }
            return res;
        }
    }

猜你喜欢

转载自blog.csdn.net/whdalive/article/details/80494719