/**
* *Test9--写一方法,打印等长的二维数组,
* 要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。
* 如: n = 4 则打印:
*/
public static void main(String[] args) {
print(1,1,2);
}
//三个参数分别为: 二维数组存储起始数,二维数组长度,二维数组中一维数组长度
private static void print(int num,int len, int line) {
int[][] arr = new int[len][line];
//time为大循环圈数
int time = len <= line ? len / 2 + len % 2 : line / 2 + line % 2;
//newLen和newLine为指针
int newLen = 0;
int newLine = 0;
for (int i = 0; i < time; i++) {
//只剩一行一列
if(line == 1 && len == 1) {
arr[newLen][newLine] = num;
//只剩一列
} else if(line == 1) {
for (int j = 0; j < len; j++) {
arr[newLen++][newLine] = num++;
}
//只剩一行
} else if(len == 1) {
for (int j = 0; j < line; j++) {
arr[newLen][newLine++] = num++;
}
}
//多行多列
if(len > 1 && line > 1) {
for (int j = 0; j < line - 1; j++) {
arr[newLen][newLine++] = num++;
}
for (int j = 0; j < len - 1; j++) {
arr[newLen++][newLine] = num++;
}
for (int j = 0; j < line - 1; j++) {
arr[newLen][newLine--] = num++;
}
for (int j = 0; j < len - 1; j++) {
arr[newLen--][newLine] = num++;
}
len -= 2;
line -= 2;
}
//指针定位
newLen++;
newLine++;
}
for (int[] is : arr) {
for (int i : is) {
System.out.print(i + "\t");
}
System.out.println();
}
} |
|