package com.heima.test.test_08;
public class PrintArrays {
/**
* 写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
*/
int width = 2;// 只能是偶数
Integer[][] Zone;
PrintArrays(int p) {
this.width = p % 2 == 1 ? p - 1 : p;
this.Zone = new Integer[this.width][this.width];
this.init(0, 1);
}
private void init(int roll, int start) {
int wid = this.width - 2 * roll;
if (wid == 0)
return;
for (int i = 0; i < wid - 1; i++) {
this.Zone[roll][i + roll] = start;
this.Zone[i + roll][this.width - 1 - roll] = start;
this.Zone[this.width - 1 - roll][this.width - 1 - roll - i] = start;
start++;
}
for (int i = 0; i < wid - 1; i++) {
start++;
}
for (int i = 0; i < wid - 1; i++) {
start++;
}
for (int i = 0; i < wid - 1; i++) {
this.Zone[this.width - 1 - roll - i][roll] = start;
start++;
}
init(++roll, start);
}
public void output() {
for (int i = 0; i < this.width; i++) {
for (int j = 0; j < this.width; j++) {
System.out.print(this.Zone[i][j]+ "\t" );
}
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintArrays x = new PrintArrays(4);
x.output();
}
}
|
|