方阵的主对角线之上称为"上三角"。
请你设计一个用于填充 n 阶方阵的上三角区域的程序。填充的规则是:使用 1,2,3.... 的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当 n=3 时,输出:
1 2 3
6 4
5
当 n=4 时,输出:
1 2 3 4
9 10 5
8 6
7
当 n=5 时,输出:
1 2 3 4 5
12 13 14 6
11 15 7
10 8
9
要求用户输入整数 n (3≤n≤20)。
输出方阵的上三角部分。
要求每个数据宽度为 4,右对齐。
输入
9
输出
- 1 2 3 4 5 6 7 8 9
- 24 25 26 27 28 29 30 10
- 23 39 40 41 42 31 11
- 22 38 45 43 32 12
- 21 37 44 33 13
- 20 36 34 14
- 19 35 15
- 18 16
- 17
- import java.util.Scanner;
- // 1:无需package
- // 2: 类名必须Main, 不可修改
-
- public class Main {
- static int[][] ans=new int[30][30];
- static int num=1;
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- int n=scan.nextInt();
- dfs(1,n);
- for(int i=1;i<=n;i++){
- for(int j=1;j<=n-i+1;j++){
- System.out.printf(ans[i][j]+" ");
- }
- System.out.println();
- }
- scan.close();
- }
- public static void dfs(int x,int n){
- if(x>n){
- return;
- }
- for(int i=x;i<=n;i++){
- ans[x][i]=num;
- num++;
- }
- int y=n;
- for(int i=x+1;i<=n;i++){
- y--;
- ans[i][y]=num;
- num++;
- }
- for(int i=n-1;i>=x+1;i--){
- ans[i][x]=num;
- num++;
- }
- dfs(x+1,n-2);
- }
- }