首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >算法练习题(六)——Z字型打印矩阵

算法练习题(六)——Z字型打印矩阵

作者头像
传说之下的花儿
发布2023-04-16 14:42:29
发布2023-04-16 14:42:29
3640
举报
代码语言:javascript
复制
/**
 *  Z字型打印矩阵
 *  1	2	3	4
 *  5	6	7	8
 *  9	10	11	12
 *  13	14	15	16
 *
 *  1	2	5	9	6	3	4	7	10	13	14	11	8	12	15	16
 */
public class TwoArraysTest03 {
    public static void main(String[] args) {
        TwoArraysTest03 twoArraysTest03 = new TwoArraysTest03();
        int [][]matrix = new int[4][4];
        int temp = 0 ;
        for (int[] ints : matrix) {
            for (int i = 0; i < ints.length; i++) {
                ints[i] = temp+1;
                temp++;
            }
        }
        twoArraysTest03.zPlainMatrix(matrix);
    }
    public void zPlainMatrix(int [] [] matrix){
        int row = 0,rowMax = matrix.length;
        int col = 0,colMax = matrix[0].length;
//        若为true 就从左下向右上打印(走上坡),反正右上向左下打印(走下坡)
        boolean liftToRight = true;
        while (row < rowMax && col <colMax){
//          走上坡
//            结果两种情况  第一种:这波上坡走完的时候的第一行 
//                          ----右走一步 col++;
//                     另一种:这波上坡走完的时候在最后一列
//                          ----下走一步 row++;
            if (liftToRight){
                System.out.print(matrix[row][col]+"\t");
//                第一种
                if (row == 0 && col < colMax-1){
//                  右走一步 便于下一波的下坡
                    col++;
//                  方向切换
                    liftToRight = false;
                    continue;
//                第二种
                }else if (row > 0 && col == colMax-1){
//                  下走一步
                    row++;
//                  切换方向
                    liftToRight = false;
                    continue;
//                走上坡的路上
                }else {
                    row--;
                    col++;
                }
//          走下坡
//             结果两种情况
//                  第一种:这波下坡走完在第一列
//                       ----下走一步 row++;
//                  第二种:这波下坡走完在最后一行
//                       ----右走一步 col++;
            }else {
                System.out.print(matrix[row][col]+"\t");
//                第一种
                if (col == 0 && row < rowMax-1){
                    row++;
                    liftToRight = true;
                    continue;
//                第二种
                }else if ( row == rowMax-1){
                    col++;
                    liftToRight = true;
                    continue;
//                在走下坡的路上
                }else {
                    row++;
                    col--;
                }
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-04-03,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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