题目
转圈打印矩阵
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);
}
}
结果