回形数
package Array;
import java.util.Scanner;
public class RectangleTest {
//回形数
/*
* 从键盘输入一个整数(1~20) ,则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。
* */
enum Direcion{Left,Right,Up,Down};
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int len=scanner.nextInt();
if(len<1 || len>20) System.out.println("请输入1-20的数字");
else huixing(len);
}
public static void huixing(int num){
int[][] arr=new int[num][num];
int row=0,col=0;
int allnum=1;
Direcion direction=Direcion.Right;
while (true){
if(direction == Direcion.Right){
if(col < num && arr[row][col] == 0){
arr[row][col++]=allnum++;
}else {
direction=Direcion.Down;
row++;
col--;
// allnum--;
}
}else if(direction == Direcion.Down){
if(row < num && arr[row][col] == 0){
arr[row++][col]=allnum++;
}else {
direction=Direcion.Left;
row--;
col--;
// allnum--;
}
}else if(direction == Direcion.Left){
if(col >=0 && arr[row][col] == 0){
arr[row][col--]=allnum++;
}else {
direction=Direcion.Up;
row--;
col++;
// allnum--;
}
}else if(direction == Direcion.Up){
if(row >=0 && arr[row][col] == 0){
arr[row--][col]=allnum++;
}else {
direction=Direcion.Right;
row++;
col++;
// allnum--;
}
}
if(allnum == num*num+1)break;
};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + "\t\t");
}
System.out.println();
}
}
}
方案2:
package Array;
public class RectangleTest1 {
public static void main(String[] args) {
int n=5;
int[][] arr = new int[n][n];
int count=0;
int MaxX=n-1;//x轴最大值
int MaxY=n-1;//y轴最大值
int MinX=0;//x轴最小值
int MinY=0;//y轴最小值
while (MinX <= MaxX){
for (int x = MinX; x <=MaxX ; x++) {
arr[MinY][x]=++count;
}
MinY++;
for (int y = MinY; y <= MaxY; y++) {
arr[y][MaxX]=++count;
}
MaxX--;
for (int x = MaxX; x >=MinX ; x--) {
arr[MaxY][x]=++count;
}
MaxY--;
for (int y = MaxY; y >=MinY ; y--) {
arr[y][MinX]=++count;
}
MinX++;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + "\t\t");
}
System.out.println();
}
}
}

浙公网安备 33010602011771号