- public class tt {
- public static void main(String[] args) {
- int[][] arr = arrs();
- for (int i = 0; i < arr.length; i++) {
- for (int j = 0; j < arr[i].length; j++) {
- if(arr[i][j]<10)
- System.out.print("0"+arr[i][j]+ " ");
- else
- System.out.print(arr[i][j]+ " ");
- }
- System.out.println();
- }
-
-
-
- }
- public static int[][] arrs() {
- // System.out.println("请输入方阵行数或列数:");
- // Scanner sc=new Scanner(System.in);
- // int le=sc.nextInt();// 数组长度
- int le=9;
- // System.out.println("请检查方阵是否正确");
-
- int arr[][] = new int[le][le];
- int x = 0;// 小数组下标,横向
- int y = 0;// 数组下标,纵向
- int n = 1;// 显示数字
-
- // 螺旋顺序是右》下》左》上》右。。
- int c = 0;// 圈数从最外面是第一圈c=0
- int t = 1;// 1右2下3左4上
- boolean b=true;
- while(b){
- while (t == 1 && x < le - c && x >= c) {
- arr[y][x++] = n++;
- //x++;
- //n++;
-
- if (x == le - c) {
-
- t = 2;
- }
- if (n == le * le+1)
- b=false;
- }
- x = le - c - 1;
- y = c + 1;
- while (t == 2 && y > c && y < le - c) {
- arr[y++][x] = n++;
- //y++;
- //n++;
- if (y == le - c) {
- t = 3;
-
- }
- if (n == le * le+1)
- b=false;
- }
- y = le - c - 1;
- x = le - c - 2;
- while (t == 3 && x < le - c - 1 && x >= c) {
- arr[y][x--] = n++;
- //n++;
- //x--;
- if (x < c) {
- t = 4;
-
- }
-
- if (n == le * le+1)
- b=false;
- }
- x = c;
- y = le - c - 2;
- while (t == 4 && y > c && y < le - c - 1) {
- arr[y--][x] = n++;
- //y--;
- //n++;
- if (y == c) {
- t = 1;
- c++;
- }
- if (n == le * le+1)
- b=false;
- }
- x = c;
- y = c;
-
-
-
- }
- return arr;
- }
-
- }
复制代码
|