Looking for commonalities from a macro level, in fact, the process of printing in circles is the process of printing peripheral elements clockwise, just give you a point in the upper left corner (such as (0,0)) and a point in the lower right corner (such as (3,3)) ), you can print out 1 2 3 4 8 12 16 15 14 13 9 5; similarly, given you (1,1) and (2,2), you can print out 6 7 11 10. This process of printing the elements on the square based on two points can be extracted, and the whole problem is solved.
public class Code_06_PrintMatrixSpiralOrder {
public static void spiralOrderPrint(int[][] matrix) {
int tR = 0;//row
int tC = 0;//column
int dR = matrix.length - 1;
int dC = matrix[0].length - 1;
while (tR <= dR && tC <= dC) {
printEdge(matrix, tR++, tC++, dR--, dC--);
}
}
public static void printEdge(int[][] m, int tR, int tC, int dR, int dC) {
if (tR == dR) {
//子矩阵只有一行时
for (int i = tC; i <= dC; i++) {
System.out.print(m[tR][i] + " ");
}
} else if (tC == dC) {
//子矩阵只有一列时
for (int i = tR; i <= dR; i++) {
System.out.print(m[i][tC] + " ");
}
} else {
//正常情况,打印一圈
int curC = tC;
int curR = tR;
while (curC != dC) {
System.out.print(m[tR][curC] + " ");//从tR行开始,往右打印至dC列
curC++;
}
while (curR != dR) {
System.out.print(m[curR][dC] + " ");
curR++;
}
while (curC != tC) {
System.out.print(m[dR][curC] + " ");
curC--;
}
while (curR != tR) {
System.out.print(m[curR][tC] + " ");
curR--;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{
1, 2, 3, 4 }, {
5, 6, 7, 8 }, {
9, 10, 11, 12 },
{
13, 14, 15, 16 } };
spiralOrderPrint(matrix);
}
}