下面附上程序,欢迎各位前来讨论:
package jian_zhi_offer;public class code29_PrintMatrixClockWisely {
public static void main(String args[]) {
int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
printMatrix(arr);
}
/* 这个函数主要是用来调用printEdge这个函数的,还有就是让转圈往里边走 */
public static void printMatrix(int arr[][]) {
if (arr == null)
return;
int row1 = 0;
int col1 = 0;
/* 取得矩阵的右下角坐标,记住,别写错了 */
int row2 = arr.length - 1;
int col2 = arr[0].length - 1;
/* 两个同时满足才可以 */
/* 转圈停止的条件~ */
while (col1 <= col2 && row1 <= row2) {
/* 调用printEdge,同时转圈往里边走 */
printEdge(arr, row1++, col1++, row2--, col2--);
}
}
/* 逻辑主要实现部分:分三种情况:只有一行,只有一列,有多行和多列 */
public static void printEdge(int arr[][], int row1, int col1, int row2, int col2) {
/* 只有一行或者只有一列的情况下,直接打印出来即可 */
if (row1 == row2) {
for (; col1 <= col2; col1++) {
System.out.print(arr[row1][col1] + " ");
}
} else if (col1 == col2) {
for (; row1 <= row2; row1++) {
System.out.print(arr[row1][col1] + " ");
}
}
/* 有多行和多列的时候,定义两个变量,来遍历整个edge元素 */
else {
int curR = row1;
int curC = col1;
while (curC != col2)
System.out.print(arr[curR][curC++] + " ");
while (curR != row2)
System.out.print(arr[curR++][curC] + " ");
while (curC != col1)
System.out.print(arr[curR][curC--] + " ");
while (curR != row1)
System.out.print(arr[curR--][curC] + " ");
}
}
}