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

    结果

  • 相关阅读:
    判断url的正则表达式
    将Excel数据导入MySql
    需要记一下的
    java笔记
    禁用cookie后
    smarty框架块函数
    php Smarty date_format [格式化时间日期]
    mysql 笔记
    笔记 php.ini配置文件中magic_quotes_gpc, magic_quotes_runtime的作用是什么?应该开启还是关闭?
    php
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8969855.html
Copyright © 2011-2022 走看看