- public class Test9 {
- /**
- * 9、 写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的
- * 最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:
- 1 2 3 4
- 12 13 14 5
- 11 16 15 6
- 10 9 8 7
- */
- public static void main(String[] args) {
- Test9 x = new Test9(6);
- x.output();
- }
- int width = 4;// 只能是偶数
- Integer[][] Zone;
- Test9(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;
- start++;
- }
- for (int i = 0; i < wid - 1; i++) {
- this.Zone[i + roll][this.width - 1 - roll] = start;
- start++;
- }
- for (int i = 0; i < wid - 1; i++) {
- this.Zone[this.width - 1 - roll][this.width - 1 - roll - i] = start;
- start++;
- }
- for (int i = 0; i < wid - 1; i++) {
- this.Zone[this.width - 1 - roll - i][roll] = start;
- start++;
- }
- init(++roll, start);
- }
- void output() {
- for (int i = 0; i < this.width; i++) {
- for (int j = 0; j < this.width; j++) {
- System.out.print("\t" + this.Zone[i][j]);
- }
- System.out.println();
- }
- }
- }
复制代码 |