给定的matrix矩阵,由内而外转圈打印元素
核心思想:将矩阵分圈、再循环打印
package com.javakk.ex;
/**
* @Time 2018年8月30日 下午3:44:17
* @Title { 转圈打印矩阵 }
* @Desc { 给定的matrix矩阵,由内而外转圈打印元素 }
* @Email 92920@sohu.com
* @Author JavaKK
*/
public class Ex12 {
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 3, 8 },
{ 2, 3, 2, 5 },
{ 3, 4, 1, 6 },
{ 4, 5, 0, 7 }
};
aroundPrint(matrix);
}
/**
* 将矩阵分圈
* @param matrix
*/
private static void aroundPrint(int[][] matrix){
int tR = 0;
int tC = 0;
int dR = matrix.length - 1;
int dC = matrix[0].length - 1;
while (tR <= dR && tC <= dC) {
printEdge(matrix, tR++, tC++, dR--, dC--);
}
}
/**
* 循环打印
* @param matrix
* @param tR : 左上row坐标
* @param tC : 左上col坐标
* @param dR : 右下row坐标
* @param dC : 右下col坐标
*/
private static void printEdge(int[][] matrix, int tR, int tC, int dR, int dC) {
if (tR == dR) {
// 只剩最后一行
for (int i = tC; i <= dC; i++) {
System.out.println(matrix[tR][i] + " ");
}
} else if (tC == dC) {
// 只剩最后一列
for (int i = tR; i <= dR; i++) {
System.out.println(matrix[i][tC] + " ");
}
} else {
// 一般情况
int curC = tC;
int curR = tR;
while (curC < dC) {
// 从左到右打印
System.out.print(matrix[tR][curC] + " ");
curC++;
}
while (curR < dR) {
// 从上到下打印
System.out.print(matrix[curR][dC] + " ");
curR++;
}
while (curC > tC) {
// 从右到左打印
System.out.print(matrix[dR][curC] + " ");
curC--;
}
while (curR > tR) {
// 从下到上打印
System.out.print(matrix[curR][tC] + " ");
curR--;
}
}
}
}