A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

输出 n=5 的螺旋方阵
        1  2  3  4  5
        16 17 18 19 6
        15 24 25 20 7
        14 23 22 21 8
        13 12 11 10 9

3 个回复

正序浏览
我看着就头晕啊
回复 使用道具 举报
好难的的说;
private static int l,r,u,d;//定义上下左右边界
        private static int[][] a=new int[0][0];//数组
        private static int y=0,x=0;//初始化坐标
        private static int step,temp;//步长,上一个数组的值
        private static void add(int y,int x){
        temp+=step;a[y][x]=temp;
        }
        private static void left(){
        while(x>l)add(y, --x);//未遇到左边界
        if(y>u){//遇到左边界且未遇到上边界
        l++;up();
        }
        }   
        private static void right(){
        while(x<r)add(y, ++x);//未遇到右边界
        if(y<d){//遇到右边界且未遇到下边界
        r--;
        down();
        }
        }   
        private static void up(){
        while(y>u)add(--y, x);//未遇到上边界
        if(x<r){//遇到上边界且未遇到右边界
        u++;
        right();
        }
        }   
        private static void down(){
        while(y<d)add(++y, x);//未遇到下边界
        if(x>l){//遇到下边界且未遇到左边界
        d--;
        left();
        }
        }
        public static void spiralArray(int start,int step,int length){//产生数组(起始值,步长,矩阵边长)
        Test9.step=step;
        l=u=0;r=d=length-1;
        a=new int[length][length];
        a[0][0]=temp=start;
        up();
        }

        public static void spiralArray(int i){
        spiralArray(0,1,i);
        }
        public static void print(){//输出矩阵
        for(int i=0;i<a.length;i++){
        for(int j=0;j<a.length;j++){
        System.out.print(a[i][j]+"\t");
        }System.out.println();}
        }

        public static void main(String[] args) {
        spiralArray(10);
        print();
        }
        }
回复 使用道具 举报
今天作业有这个,不会写。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马