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

题目

"之"字形打印矩阵

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);
    }
}

结果

posted @ 2018-04-29 07:36  lizhouwei  阅读(205)  评论(0编辑  收藏  举报