螺旋矩阵

alt

    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> order = new ArrayList<Integer>();//用来保存遍历的结果集

        //判空
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }

        //记录行数,和列数
        int rows = matrix.length, columns = matrix[0].length;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;

        while (left <= right && top <= bottom) {
            //1.(top,left)--->(top,right)
            for (int column = left; column <= right; column++) {
                order.add(matrix[top][column]);
            }
            //2.(top,right)-->(bottom,right)
            for (int row = top + 1; row <= bottom; row++) {
                order.add(matrix[row][right]);
            }
            //判断左下方的情况
            if (left < right && top < bottom) {//在此种情况下才有输出
                //3.(bottom,right)--->(bottom,left)
                for (int column = right - 1; column > left; column--) {
                    order.add(matrix[bottom][column]);
                }
                //4.(bottom,left)--->(top,left)
                for (int row = bottom; row > top; row--) {
                    order.add(matrix[row][left]);
                }
            }
            //一层遍历完成之后,缩小范围。
            left++;
            right--;
            top++;
            bottom--;
        }

        return order;
    }
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务