27 蛇形方阵

27 蛇形方阵

作者: Turbo时间限制: 1S章节: 二维数组

问题描述 :

输出一个如下的n阶方阵。例如,若读入11,则输出:

无标题.png

输入说明 :

输入一个正整数n(n<20),表示需要输出n阶方阵。

输出说明 :

共输出n行n列,每个整数占4位,不足4位则左边补空格。

每行的最后无空格。

无多余空行。

输入范例 :

11
输出范例 :

1 2 3 4 5 6 7 8 9 10 11
22 21 20 19 18 17 16 15 14 13 12
23 24 25 26 27 28 29 30 31 32 33
44 43 42 41 40 39 38 37 36 35 34
45 46 47 48 49 50 51 52 53 54 55
66 65 64 63 62 61 60 59 58 57 56
67 68 69 70 71 72 73 74 75 76 77
88 87 86 85 84 83 82 81 80 79 78
89 90 91 92 93 94 95 96 97 98 99
110 109 108 107 106 105 104 103 102 101 100
111 112 113 114 115 116 117 118 119 120 121

import java.util.Scanner;

public class test_27 {
    /**
     * 27 蛇形方阵
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int num=n*n,count=1,start=1;
        char state = 'r';
        while(start<=num){
            switch (state){
                case 'r':
                    if(count!=0 && count%n==0){
                        state='l';
                        System.out.printf("%4d\n",start);
                        start+=n;
                        count=1;
                    }else{
                        count++;
                        System.out.printf("%4d",start++);
                    }
                    break;
                case 'l':
                    if(count!=0 && count%n==0){
                        state='r';
                        System.out.printf("%4d\n",start);
                        start+=n;
                        count=1;
                    }else{
                        count++;
                        System.out.printf("%4d",start--);
                    }
                    break;
                default:
                    System.out.println();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值