面试题:
给你4,程序输出:
01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07
给你5,程序输出:
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09
不难发现其实就是一个环形矩阵问题,规律就是它需要在哪里转变打印方向
从上图可以得出转头的规律
public class PrintCircularMatrix {
public static void main(String[] args) {
int SIZE = 6;
int[][] arr = new int[SIZE][SIZE]; // 创建了一个二维数组
//默认向下
int orient = 0; // 0代表向下,1代表向右,2代表向上,3代表向左
for(int i=1,row=0,col=0;i<=SIZE*SIZE;i++){
arr[row][col]=i;
// 位于①号对角线的 下一半
if(row+col==SIZE-1&&row>=SIZE/2){
orient=1;
}
// 位于①号对角线的 上一半
if(row+col==SIZE-1&&row<SIZE/2){
orient=3;
}
// 位于②号对角线的 下一半
if(row==col&&row>=SIZE/2){
orient=2;
}
if(col-row==1&&row<SIZE/2){
orient = 0;
}
switch (orient) {
case 0:
row++;
break;
case 1:
col++;
break;
case 2:
row--;
break;
case 3:
col--;
break;
}
}
//循环打印
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (arr[i][j] < 10) {
System.out.print("0" + arr[i][j] + "\t");
} else {
System.out.print(arr[i][j] + "\t");
}
}
System.out.println();
}
}
}