找规律-螺旋矩阵

2024-07-14  本文已影响0人  今夜秋风和

螺旋矩阵

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

题目分析

跟螺旋矩阵类似,顺时针先打印最外圈元素,然后顶点索引递进,打印内圈元素,在打印一圈元素时,分别沿着4个方向打印,然后继续打印内圈元素;

截屏2024-07-15 上午8.01.18.png

编程实现

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList();
        if(matrix == null || matrix.length <= 0){
            return list;
        }
        int left = 0;
        int right = matrix[0].length-1;
        int bottom = matrix.length - 1;
        int top = 0;
        while(left <= right && top <= bottom){
            //打印行
            for(int i = left;i <= right;i++){
                list.add(matrix[top][i]);
            }
            //打印右侧
            for(int i = top+1;i <= bottom;i++){
                list.add(matrix[i][right]);
            }
            //打印最底行,top!= bottom ,只有一行情况下 6 7 9
            if(top != bottom){
                for(int i = right -1;i >= left;i--){
                    list.add(matrix[bottom][i]);
                }
            }
            
            /**
             打印最左侧 left!=right 条件,只有一列情况下
             6
             7
             9
             */
            if(left != right){
                for(int i = bottom -1;i > top;i--){
                    list.add(matrix[i][left]);
                }
            }
            left++;
            right--;
            bottom--;
            top++;
        }
        return list;
    }

上一篇 下一篇

猜你喜欢

热点阅读