《程序员代码面试指南》第八章 数组和矩阵问题 "之"字形打印矩阵

之字形打印矩阵
本文介绍了一种使用Java实现的之字形打印矩阵的方法。通过定义特定的上下文方向,该算法能够按之字形路径遍历二维矩阵,并打印出相应元素。示例代码展示了如何创建和调用此功能。
题目
"之"字形打印矩阵
java代码
package com.lizhouwei.chapter8;

/**
 * @Description: "之"字形打印矩阵
 * @Author: lizhouwei
 * @CreateDate: 2018/4/28 22:53
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter8_3 {
    public void printMatrixZigZag(int[][] matrix) {
        int tR = 0;
        int tC = 0;
        int dR = 0;
        int dC = 0;
        int endR = matrix.length - 1;
        int endC = matrix[0].length - 1;
        boolean UToD = false;
        while (tR <= endR) {
            printZigZag(matrix, UToD, tR, dR, tC, dC);
            tR = tC == endC ? tR + 1 : tR;
            tC = tC == endC ? tC : tC + 1;
            dC = dR == endR ? dC + 1 : dC;
            dR = dR == endR ? dR : dR + 1;
            UToD = !UToD;
        }
    }

    public void printZigZag(int[][] matrix, boolean UToD, int tR, int dR, int tC, int dC) {
        if (UToD) {
            while (tR != dR+1 ) {
                System.out.print(matrix[tR++][tC--]+" ");
            }
        } else {
            while (tR  != dR+1) {
                System.out.print(matrix[dR--][dC++]+" ");
            }
        }
        System.out.println();
    }

    //测试
    public static void main(String[] args) {
        Chapter8_3 chapter = new Chapter8_3();
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        chapter.printMatrixZigZag(matrix);
    }
}
结果

1369004-20180429073612308-277390359.png

转载于:https://www.cnblogs.com/lizhouwei/p/8970301.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值