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

“之”字形打印矩阵

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

【题目】 给定一个矩阵matrix,按照“之”字形的方式打印这 个矩阵,例如: 1 2 3 4 5 6 7 8 9 10 11 12 “之”字形打印的结果为:1,2,5,9,6,3,4,7,10,11, 8,12 【要求】 额外空间复杂度为O(1)。

算法实现思想 定义一个A点从左上角先沿着左边框移动,到最下一点时候向右移动 定义一个B点从左上角先沿着上边框移动,到最右一点时候向下移动 打印每次移动后,两者之间的数字;

代码

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

public class  PrintMatrixZigZag{
   public static void printMatrixZigZag(int[][] matrix) {
        //A点
        int aR=0;
        int aC=0;
        //B点
        int bR=0;
        int bC=0;
        int endR=matrix.length-1;//结束行索引
        int endC=matrix[0].length-1;//结束列索引
       boolean upFlag=true;
        while (aC!=endC+1){
            printSlash(matrix,aR,aC,bR,bC,upFlag);
           //{   1, 2,  3,  4   },
           //{   5, 6,  7,  8   },
           //{   9, 10, 11, 12  },
           //{   13,14, 15, 16  }
            if (aR<endR){
                aR++;
            }else {
                aC++;
            }
            if (bC<endC){
                bC++;
            }else {
                bR++;
            }
            upFlag=!upFlag;
        }

    }
    public static void  printSlash(int[][] matrix,int aR,int aC ,int bR,int bC,boolean upFlag){ //打印AB之间斜线上的数字
        if (upFlag){
            int currR=aR;
            int currC=aC;
            for(int i=aR;i>=bR;i--){
                System.out.println(matrix[currR][currC]+" ");
                currR--;
                currC++;
            }
        }else {
            int currR=bR;
            int currC=bC;
            for(int i=bC;i>=aC;i--){
                System.out.println(matrix[currR][currC]+" ");
                currR++;
                currC--;
            }
        }
    }
    public static void main(String[] args){
        int [][] matrix = {
                {   1, 2,  3,  4   },
                {   5, 6,  7,  8   },
                {   9, 10, 11, 12  },
                {   13,14, 15, 16  }
        };
        printMatrixZigZag(matrix);
      
    }

}

打印结果

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

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

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

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

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