算法-转圈打印矩阵

题目

给定一个整型矩阵matrix,请按照转圈的方式打印它。要求额外空间复杂度为O(1)。
例如:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
打印结果为1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12

思路
题意为从左上角(a,b)开始转圈打印矩阵在这里插入图片描述
这道题我们只需要考虑重要的几个边界即可。首先根据左上角(a,b)和右下角(c,d)确定这个矩阵,以顶点(x,y)开始沿着打印路线开始移动打印,开始(x,y)向右移动(x++),当到达右边界d时向下移动(y++),到达下边界c时向左移动(x--),到达左边界b时向上移动(y++),以此类推
在这里插入图片描述
代码

/**
 * 转圈打印矩阵
 * 【题目】 给定一个整型矩阵matrix,请按照转圈的方式打印它。
 * 例如:1	2	3	4	5	6	7	8	9	10	11	12	13	14	15	16	17	18	19	20
 * 打印结果为:1	2	3	4	5	10	15	20	19	18	17	16	11	6	7	8	9	14	13	12
 * 【要求】 额外空间复杂度为O(1)。
 *
 * @Author: FangJu
 * @Date: 2019/8/11
 */
public class PrintMatrixSpiralOrder {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4, 5},
                {6, 7, 8, 9, 10},
                {11, 12, 13, 14, 15},
                {16, 17, 18, 19, 20}
        };

        spiralOrderPrint(matrix);
    }

    /**
     * 转圈打印矩阵
     *
     * @param matrix 矩阵
     */
    private static void spiralOrderPrint(int[][] matrix) {
        int a = 0;
        int b = 0;
        int c = matrix.length - 1;
        int d = matrix[0].length - 1;
        while (a <= c && b <= d) {
            printEdge(matrix, a++, b++, c--, d--);
        }
    }

    /**
     * 顺时针旋转打印
     * (a,b)左上角坐标
     * (c,d)右下角坐标
     *
     * @param matrix 矩阵
     * @param a      矩阵左上角行
     * @param b      矩阵左上角列
     * @param c      矩阵右下角行
     * @param d      矩阵右下角列
     */
    private static void printEdge(int[][] matrix, int a, int b, int c, int d) {
        if (a == c) {//只有一行
            while (b <= d) {
                System.out.print(matrix[a][b++] + "\t");
            }
        } else if (b == d) {//只有一列
            while (a <= c) {
                System.out.print(matrix[a++][b] + "\t");
            }
        } else {
            int x = b;
            int y = a;
            while (x < d) {
                System.out.print(matrix[a][x++] + "\t");
            }
            while (y < c) {
                System.out.print(matrix[y++][d] + "\t");
            }
            while (x > b) {
                System.out.print(matrix[c][x--] + "\t");
            }
            while (y > a) {
                System.out.print(matrix[y--][b] + "\t");
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值