Spiral Matrix I & II 螺旋矩阵

https://leetcode-cn.com/problems/spiral-matrix/

image.png

(图片来源https://leetcode-cn.com/problems/spiral-matrix/

日期 是否一次通过 comment
2020-02-24 手不熟,忘了最外边的循环体

public List spiralOrder(int[][] matrix) {
        List res = new ArrayList<>();
        if(matrix == null || matrix.length < 1 || matrix[0].length < 1) {
            return res;
        }

        int rMax = matrix.length-1, cMax = matrix[0].length-1;
        int rSta = 0, cSta = 0;
        while(rSta <= rMax && cSta <= cMax) {
            if(cSta <= cMax) {
                for(int c=cSta; c<=cMax; c++) {
                    res.add(matrix[rSta][c]);
                }
                
                rSta ++;
            }

            if(rSta <= rMax) {
                for(int r=rSta; r<=rMax; r++) {
                    res.add(matrix[r][cMax]);
                }

                cMax --;
            }

            if(rSta <= rMax) {
                for(int c=cMax; c>=cSta; c--) {
                    res.add(matrix[rMax][c]);
                }

                rMax --;
            }

            if(cSta <= cMax) {
                for(int r=rMax; r>=rSta; r--) {
                    res.add(matrix[r][cSta]);
                }

                cSta ++;
            }
        }

        return res;
    }

旋转数组二:
生成[1, n],以螺旋数组的格式填充数组

https://leetcode-cn.com/problems/spiral-matrix-ii/


 public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int rSta = 0, cSta = 0;
        int rEnd = n-1, cEnd = n-1;
        int v = 1;

        while(rSta<=rEnd && cSta<=cEnd) {
            for(int i=cSta; i<=cEnd; i++) {
                res[rSta][i] = v;
                v ++;
            }
            rSta ++;

            for(int i=rSta; i<=rEnd; i++) {
                res[i][cEnd] = v;
                v ++;
            }
            cEnd -- ;

            if(rSta <= rEnd) {
                for(int i=cEnd; i>=cSta; i--) {
                    res[rEnd][i] = v;
                    v++;
                }
                rEnd --;
            }

            if(cSta <= cEnd) {
                for(int i=rEnd; i>=rSta; i--) {
                    res[i][cSta] = v;
                    v++;
                }

                cSta ++;
            }
        }

        return res;
    }

你可能感兴趣的:(Spiral Matrix I & II 螺旋矩阵)