用二维数组输出螺旋方阵(JAVA实现)

 

思路一:

public class Main {
    public static void main(String[] args) throws IOException{
        int[][] a = print(8);
        for(int[] el : a) {
            for(int e : el) {
                System.out.printf("%4d", e);
            }
            System.out.println("");
        }
    } 
    
    public static int[][] print(int n) {
        int[][] array = new int[n][n];
        int count = 0; //层数
        int f = 0;
        while(count<n/2) {
            for(int i=0; i<n-2*count-1; i++) {
                array[count][count+i] = 1+i+f; //上侧-从左到右
                array[count+i][n-count-1] = (1+i+f)+(n-2*count-1); //右侧-从上到下
                array[n-count-1][n-1-count-i] = (1+i+f)+2*(n-2*count-1); //下侧-从右到左
                array[n-1-count-i][count] = (1+i+f)+3*(n-2*count-1); //左侧-从下到上
            }
            count++;
            f += 4*(n-2*count+1);
        }
        if(n%2==1) {
            array[n/2][n/2] = (int) Math.pow(n, 2);
        }
        return array;
    }
    
}

思路二:

public static int[][] printMatrix(int n) {
        int[][] res = new int[n][n];
        int left=0;
        int top=0;
        int right=n-1;
        int bottom=n-1;
        int count = 1;
        while(left<=right&&top<=bottom) {
            for(int j=left; j<=right; j++) {
                res[top][j]=count++;
            }
            for(int i=top+1; i<=bottom; i++) {
                res[i][right]=count++;
            }
            if(top!=bottom) {
                for(int j=right-1; j>=left; j--) {
                    res[bottom][j]=count++;
                }
            }
            if(left!=right) {
                for(int i=bottom-1; i>top; i--) {
                    res[i][left]=count++;
                }
            }
            
            left++;
            top++;
            right--;
            bottom--;
        }
        return res;
    }

output:

   1   2   3   4   5   6   7   8

  28  29  30  31  32  33  34   9

  27  48  49  50  51  52  35  10

  26  47  60  61  62  53  36  11

  25  46  59  64  63  54  37  12

  24  45  58  57  56  55  38  13

  23  44  43  42  41  40  39  14

  22  21  20  19  18  17  16  15

转载请注明出处

转载于:https://www.cnblogs.com/macyzhang/p/9877592.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值