螺旋二维数组

来源:互联网 发布:淘宝网宝贝主图尺寸 编辑:程序博客网 时间:2024/05/19 23:58
package cn.bjsxt.luoxuan;import java.util.Scanner;public class LuoXuan{    //检测边界与是否该方向下一个已赋值    //返回方向    public static int checkBounds(int direction, int height, int width, int[][] array){        int len=array.length;        if(direction==4){            if(width == len-1 || array[width+1][height]!=0){                direction=2;            }        }else if(direction == 2){            if(height==0 || array[width][height-1]!=0){                direction=3;            }        }else if(direction == 3){            if(width==0 || array[width-1][height]!=0){                direction=1;            }        }else if(direction == 1){            if(height==len-1 || array[width][height+1]!=0){                direction=4;            }        }        return direction;    }    public static void setNum(int[][] array){        int len=array.length;        int num=1;        int height=0;        int width=0;        int direction=1;   //1 向右  2向左  3向上 4向下        for(int i=0;i<len*len;i++){            if(i==0){                array[width][height] = num;                num++;            }            if(direction==1 ){                height++;            }else if(direction == 2){                height--;            }else if(direction == 3){                width--;            }else if(direction == 4){                width++;            }            direction=checkBounds(direction,height,width,array);            //赋值            array[width][height] = num;            num++;        }    }    public static void main(String[] args) {        System.out.println("请输入数组的宽度");        Scanner scanner = new Scanner(System.in);         int len=scanner.nextInt();        int[][] array=new int[len][len];        setNum(array);        for (int i = 0; i < array.length; i++) {            for (int j = 0; j < array[i].length; j++) {                System.out.print(array[i][j]+"\t");            }            System.out.println();        }    }}

这里写图片描述

原创粉丝点击