A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 潘_洋 中级黑马   /  2015-11-10 16:20  /  784 人查看  /  1 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. /*
  2. * 写一方法,打印等长的二维数组,
  3. * 要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。
  4. *  如: n = 4 则打印:
  5. *   1    2    3    4
  6. *   12   13   14   5
  7. *   11   16   15   6
  8. *   10   9    8    7
  9. */
  10. import java.util.Scanner;
  11. public class Test9 {
  12.         public static void main(String[] args) {
  13.                 Scanner sc=new Scanner(System.in);
  14.                 System.out.println("请输入一个正整数:");
  15.                 int n=sc.nextInt();
  16.                 int[][] arr=new int[n][n];
  17.                 //每一圈左上角数字最小
  18.                 int min=1;
  19.                 //圈数
  20.                 int count=0;
  21.                 print(n,arr,min,count);
  22.                 //遍历打印二维数组
  23.                 for(int[] ar : arr){  
  24.             for(int a : ar){  
  25.                 if(a<10)  
  26.                     System.out.print(" "+a+" ");  
  27.                 else  
  28.                     System.out.print(a+" ");  
  29.             }  
  30.             System.out.println();  
  31.         }  
  32.                 /*for(int i=0;i<n;i++){
  33.                         System.out.println(Arrays.toString(arr[i])+"\t");
  34.                 }*/
  35.         }
  36.         public static void print(int n,int[][] arr,int min,int count){
  37.                 for (int i = 0; i <=(n-1)*4; i++) {
  38.                         if (n==0) {//当输入0时直接跳出循环
  39.                                 System.out.println("您的输入有误");
  40.                         }else{
  41.                                 if (n==1) {//当输入1时,打印1
  42.                                         arr[count][count]=min;
  43.                                         break;
  44.                                 }
  45.                         }
  46.                         //n-1个为一组,一共赋值4组
  47.                         if(i<n-1){//第一组,向右赋值
  48.                                 arr[count][count+i%(n-1)] = min++;
  49.                         } else if (i<(n-1)*2){//第二组,向下赋值
  50.                                 arr[count+i%(n-1)][count+n-1] = min++;
  51.                         } else if (i<(n-1)*3) {//第三组,向左赋值
  52.                                 arr[count+n-1][count+n-1-i%(n-1)] = min++;
  53.                         } else if (i<(n-1)*4){//第四组,向上赋值
  54.                                 arr[count+n-1-i%(n-1)][count] = min++;
  55.                         } else {
  56.                                 //当一圈赋值完毕,圈数加一,边长减二,递归调用
  57.                                 print(n-2,arr,min,++count);                                       
  58.                         }
  59.                 }
  60.                
  61.         }
  62. }
复制代码

1 个回复

倒序浏览
这个做过了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马