螺旋矩阵算法

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

 

 

public static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();//输出列表
        if (matrix == null) {

            return order;
        }
        int rows = matrix.length;//matrix的行数
        int cols  = matrix[0].length;//matrix的列数
        int top = 0,left = 0,right = cols-1,bottom = rows-1;

        while (top<=bottom&&left<=right){
            for(int col = left;col<=right;col++){
                order.add(matrix[top][col]);

            }
            for(int row =top+1;row<=bottom;row++){
                order.add(matrix[row][right]);
            }
            if(left<right&&top<bottom){
                for(int col = right-1;col>=left;col--){
                    order.add(matrix[bottom][col]);
                }
                for(int row = bottom-1;row>top;row--){
                    order.add(matrix[row][left]);
                }
            }
            top++;left++;
            right--;bottom--;
            }




        return order;
    }

 

 螺旋矩阵的想法:

首先最外一层节点遍历1,然后中间一层节点遍历2,最内侧一层节点遍历3.

posted @ 2021-03-15 21:03  chenyuan#  阅读(495)  评论(0)    收藏  举报