leetcode-54 Spiral Matrix

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38340127/article/details/89971058

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]

根据题意就是螺旋读取结果值:(注意一些情况 会重复读取)

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
                if(matrix == null || matrix.length == 0 ) {
            return res;
        }
        getRes(0,0,res,matrix);
        
        return res;
        
    }
    
    public void getRes(int beginI, int beginJ, List<Integer> res, int[][] matrix) {
        int i = beginI;
        int j = beginJ;
        if(i>= matrix.length-beginI || j >=matrix[i].length-beginJ ) {
            return;
        }
        res.add(matrix[i][j]);
        
        
        boolean right = false;

        while (j < matrix[i].length - beginJ - 1) {
                res.add(matrix[i][++j]);
                right = true;
        }

        while (i < matrix.length - beginI - 1 ) {
                res.add(matrix[++i][j]);
        }
        while (j > beginJ && i!= beginI) {
                res.add(matrix[i][--j]);
        }

        
        while(i > beginI+1 && j == beginJ && right) {
            res.add(matrix[--i][j]);
        }
        
        
        if (i > beginI && j == beginJ ) {
            getRes(beginI + 1, beginJ + 1, res, matrix);
        }
                    


    }

猜你喜欢

转载自blog.csdn.net/qq_38340127/article/details/89971058