篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《程序员代码面试指南》第八章 数组和矩阵问题 转圈打印矩阵相关的知识,希望对你有一定的参考价值。
题目
转圈打印矩阵
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);
}
}
结果