[编程题]输出蛇形数组 Java版

题目:输入一个数n,输出n*n的蛇形数组。如输入n = 5,输出:

1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8

这道题主要是考虑边数组的边界问题,我们可以先一环一环的进行数组的赋值,代码如下:


import java.util.*;

public class Main{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            int count = 1; //给数组赋值的数字
            int[][] arr = new int[n][n];
            for (int start = 0; start * 2 < n; start++) {
                int end = n - 1- start;
                for (int i = start; i < end; i++) { //对最上面的一行进行从左到右赋值
                    arr[start][i] = count++;
                }
                for (int i = start; i < end; i++) { //对最右边的一列进行从上到下赋值
                    arr[i][end] = count++;
                }
                for (int i = end; i > start; i--) { //对最下边的一行进行从右到左赋值
                    arr[end][i] = count++;
                }
                for (int i = end; i > start; i--) { //对最左边的一列进行从上到下赋值
                    arr[i][start] = count++;
                }
            }

            if (n%2 != 0) { //判断n是否为奇数,是的话就要对数组最中间那个元素赋值
                arr[n/2][n/2] = count;
            }

            for (int i = 0; i < arr.length; i++) { //输出
                for (int j = 0; j < arr.length; j++) {
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println("");
            }

        }
        sc.close();
    }

}

结果:
这里写图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值