螺旋数组

问题描述

eg:
输入 3
输出
1 2 3
8 9 4
7`6 5

import java.util.Scanner;
class Main02{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] data = new int[n+1][n+1];

        int i = 1;
        int j = 1;
        for(i=1;i<=n;i++){
            for (j=1; j<=n;j++ ) {
                data[i][j] = 0;
            }
        }
        i=j=1;
        int num = 0;
        if(n%2!=0) data[n/2+1][n/2+1] = n*n;
        //System.out.println( data[n/2+1][n/2+1]);
        for(int k=1;k<=n/2;k++)//k表示层数
        {
            for(j=k;j<=n-k;j++)
                data[i][j] = ++num;
            for(i=k;i<=n-k;i++)
                data[i][j] = ++num;
            for(j=n-k+1;j>=k+1;--j)
                data[i][j] = ++num;
            for(i=n-k+1;i>=k+1;i--)
                data[i][j] = ++num;
            i++;
            j++;
        }


        for(i=1;i<=n;i++){
            for (j=1; j<=n;j++ ) {
                System.out.printf("%4d",data[i][j]);
            }
            System.out.println();
        }
    }
}
posted @ 2016-10-14 10:14  岳麓丹枫  阅读(151)  评论(0编辑  收藏  举报