给你一个正整数 n ,生成一个包含 1 到 n的平方 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形二维整型数组 matrix ,并将其打印出来.
例:
输入n = 3
那么我们应该生成的二维数组是:
提示:
1<= n <= 20;
package com.atamy.wintervacation.dailyoneproblem; import java.util.Scanner; public class Day01 { public static void main(String[] args){ Scanner scan = new Scanner(System.in); Day01 day01 = new Day01(); System.out.println("请输入一个整数:"); int n; n = scan.nextInt(); int[][] huiXing = new int[n][n]; day01.method1(n,huiXing); day01.method2(n,huiXing); } public void method1(int n,int[][] huiXing){ int flag = 1 ,num = 1 ,i = 0 ,j = 0 ,count = 0,max = n*n; while(count < max){ switch(flag){ case 1: for(int k = 0;k < n;k ++,j ++,num ++){ huiXing[i][j] = num; count ++; } n --; i ++; j --; flag = 2; break; case 2: for(int k = 0;k < n;k ++,i ++,num ++){ huiXing[i][j] = num; count ++; } i --; j --; flag =3; break; case 3: for(int k = 0;k < n;k ++,j --,num ++){ huiXing[i][j] = num; count ++; } n --; i --; j ++; flag = 4; break; case 4: for(int k = 0;k < n;k ++,i --,num ++){ huiXing[i][j] = num; count ++; } j ++; i ++; flag = 1; break; } } } public void method2(int n,int[][] huiXing){ for(int i = 0;i < n;i ++){ for(int j = 0;j < n;j ++){ System.out.print(huiXing[i][j]+"t"); } System.out.println(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)