zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第八章 数组和矩阵问题 转圈打印矩阵

    题目

    转圈打印矩阵
    

    java代码

    package com.lizhouwei.chapter8;
    
    /**
     * @Description: 转圈打印矩阵
     * @Author: lizhouwei
     * @CreateDate: 2018/4/28 21:52
     * @Modify by:
     * @ModifyDate:
     */
    public class Chapter8_1 {
    
        public void printMatrix(int[][] matrix) {
            int tR = 0;
            int tC = 0;
            int dR = matrix.length - 1;
            int dC = matrix[0].length - 1;
            while (tR < dR) {
                printLToR(matrix, tR++, dR, tC, dC);
                printUToD(matrix, tR, dR, tC, dC--);
                printRToL( matrix,   tR,   dR--,   tC,   dC);
                printDToU( matrix,   tR,   dR,   tC++,   dC);
            }
        }
    
        private void printLToR(int[][] matrix, int tR, int dR, int tC, int dC) {
            while (tC <= dC) {
                System.out.print(matrix[tR][tC++] + " ");
            }
            System.out.println();
    
        }
    
        private void printUToD(int[][] matrix, int tR, int dR, int tC, int dC) {
            while (tR <= dR) {
                System.out.print(matrix[tR++][dC] + " ");
            }
            System.out.println();
        }
    
        private void printRToL(int[][] matrix, int tR, int dR, int tC, int dC) {
            while (tC <= dC) {
                System.out.print(matrix[dR][dC--] + " ");
            }
            System.out.println();
    
        }
        private void printDToU(int[][] matrix, int tR, int dR, int tC, int dC) {
            while (tR <= dR) {
                System.out.print(matrix[dR--][tC] + " ");
            }
            System.out.println();
        }
    
        //测试
        public static void main(String[] args) {
            Chapter8_1 chapter = new Chapter8_1();
            int[][] matrix = {{1, 2, 3, 4, 5}, {14, 15, 16, 17, 6}, {13, 20, 19, 18, 7}, {12, 11, 10, 9, 8}};
            chapter.printMatrix(matrix);
        }
    }
    
    

    结果

  • 相关阅读:
    通过 AWS CLI 操作 AWS S3
    AWS S3文件存储服务器搭建(新)
    Vertx 接入MongoDB (九)
    Vertx 接入Redis (八)
    Vertx Mysql数据库优化 (七)
    Vertx 接入Mysql数据库 (六)
    Vertx 实现webapi实战项目(五)
    Vertx 实现webapi实战项目(四)
    Vertx 实现webapi实战项目(三)
    正则表达式:元字符(基本可用来匹配的字符)
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8969855.html
Copyright © 2011-2022 走看看