前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >转圈打印矩阵

转圈打印矩阵

作者头像
名字是乱打的
发布2022-05-13 10:00:29
2050
发布2022-05-13 10:00:29
举报
文章被收录于专栏:软件工程

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

打印顺序

实现思想 我们可以定义两个点,一个是左上角的点(tR,tC),一个是右下角的点(dR,dC),利用这两个点即可确定矩阵的一个四周边界,我们可以利用这两个点来打印这四周边界,而里面的值,只需要我们往内挪动这两个点到里面小矩阵的两个角,继续打印. 代码

代码语言:javascript
复制
package com.day1.practice;


public class PrintEdge {
    public static void  spiralOrderPrint(int[][] matrix){
        //       (tR,tC)
        //
        //
        //
        //                        (dR,dC)
        int tR=0;//矩阵左上角的行坐标
        int tC=0;//矩阵左上角的列左边
        int dR=matrix.length-1;   //矩阵右下角的行坐标
        int dC=matrix[0].length-1;//矩阵右下角的列左边
        while (tR<=dR&&tC<=dC){
        prindEdge(matrix,tR,tC,dR,dC);
        tR++;tC++;
        dR--;dC--;
        }
    }
    public static void  prindEdge(int[][] matrix, int tR,int tC,int dR,int dC){
        if (tR==dR&&tC==dC){ //同点
        System.out.print(matrix[0][0]+" ");
        }
        if (tR==dR&&tC!=dC)//同行不同列
        {
            for(int i=tC;i<=dC;i++){
                System.out.print(matrix[tR][i]+" ");
            }
        }
        if (tC==dC&&tR!=dR)//同列不同行
        {
            for(int i=tR;i<=dR;i++){
                System.out.print(matrix[i][tC]+" ");
            }
        }
        if (tC!=dC&&tR!=dR){//不同列不同行
            //       (tR,tC)
            //
            //
            //
            //                        (dR,dC)
            int currC=tC;
            int currR=tR;
            while (currC!=dC) { //打印上边框
                System.out.print(matrix[tR][currC]+" ");
                currC++;
            }
            while (currR!=dR){//打印右边框
                System.out.print(matrix[currR][dC]+" ");
                currR++;
            }
            while (currC!=tC){//打印下边框
                System.out.print(matrix[currR][currC]+" ");
                currC--;
            }
            while (currR!=tR){//打印左边框
                System.out.print(matrix[currR][currC]+" ");
                currR--;
            }
        }
    }
    public static void main(String[] args){
        int [][] matrix = {
                {   1, 2,  3,  4   },
                {   5, 6,  7,  8   },
                {   9, 10, 11, 12  },
                {   13,14, 15, 16  }
        };
        spiralOrderPrint(matrix);
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档