zoukankan      html  css  js  c++  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);
        }
    }
    

    结果

  • 相关阅读:
    [转载]c++转python
    [转载]One-hot编码
    [转载]各种机器学习算法的应用场景
    SVC和SVR
    机器学习-正则化+回归与分类辨析
    C#编译时,提示缺少NuGet包
    C++中 左值和右值的区别
    C++11并发编程实战 免费书籍
    静态库和动态库
    C++中string类
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8970301.html
Copyright © 2011-2022 走看看