用二维数组输出螺旋方阵(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;
    }
    
}

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

扫描二维码关注公众号,回复: 3767247 查看本文章

转载请注明出处

猜你喜欢

转载自www.cnblogs.com/macyzhang/p/9877592.html