蛇形环绕。又叫上三角算法

方阵的主对角线之上称为“上三角”。

请你设计一个用于填充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~20)

程序输出:方阵的上三角部分。

要求格式:每个数据宽度为4,右对齐。

要求考生把所有类写在一个文件中。调试好后,存入与考生文件夹下对应题号的“解答.txt”中即可。相关的工程文件不要拷入。请不要使用package语句。

另外,源程序中只能出现JDK1.5中允许的语法或调用。不能使用1.6或更高版本。

图片

import java.io.*;
public class Triangle
{
    public static void main(String[] args) throws IOException
    {
        new CarryOut().Execute();
    }
}
class CarryOut
{
    public void Execute() throws IOException
    {
        BufferedReader ch=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("请输入一个数:");
        int n=Integer.parseInt(ch.readLine()); // n == 4
        int[][] nn=new int[n][n];
        int number=1;
        int t=0;
        if(n==1)
        {
            System.out.print(1);
            return ;
        }
        for(int i=0;i<n;i++) // 0 =< i < 4
        {
            boolean Judge=true;
            for(int x=t;x<n-2*t-1;x++) //x=1            1<3
            {
                Judge=false;
                nn[t][x]=number++;
            }
            for(int y=t,tt=n-t*2-1;y<n-2*t-1;y++) // y=1           y<2
            {
                Judge=false;
                nn[y][tt]=number++;
                tt--;
            }
            for(int z=n-2*t-1;z>=t+1;z--)
            {
                Judge=false;
                nn[z][t]=number++;
            }
            if(Judge && n!=2)
            {
                nn[t][t]=number;
                break;
            }
            if(t>n/2)
            {
                break;
            }
            t++;
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(nn[i][j]!=0)
                {
                    System.out.print(String.format("%-5d", nn[i][j]).toString());
                }
            }
            System.out.println()    ;
        }
    }
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值