package com.itheima;
import java.util.Scanner;
/*
7、写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
*/
public class Test7 {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.println("请输入数字:");
int n = sc.nextInt();
test(n);
}
public static void test(int n) {
int[][] t2 = new int[n][n];
boolean left = true;// true从左到右打印然后从上到下 false 从右到左 然后从下到上
int x = 0;// x轴
int y = 0;// y轴4
for (int i = 1; n >= 0; n--) {// i是要打印的数字
if (left) {//
// 总共要打印的数量 2n-1
int t = 2*n - 1;
for (int j = 0; j < t; j++) {
if (j > 0)// 第一次不偏移
if (j > t / 2) {
// 从上往下偏移
y++;
} else {
// 从左往右偏移
x++;
}
t2[y][x] = i++;
}
x--;// 矫正头的位置(就是第一要打的)
left = !left;
} else {
int t = 2*n - 1;
for (int j = 0; j < t; j++) {
if (j > 0)
if (j > t / 2) {
// 从下往上
y--;
} else {
// 从右向左
x--;
}
t2[y][x] = i++;
}
x++;// 矫正打印位置
left = !left;
}
}
System.out.println();
for (int i = 0; i < t2.length; i++) {
for (int j = 0; j < t2[i].length; j++) {
System.out.print( t2[i][j]+"\t");
}
System.out.println();
}
}
}
|
|