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();
}
}
}
螺旋二维数组
最新推荐文章于 2025-05-18 12:17:21 发布