import java.util.Scanner;
public class learn {
public static void main(String[] args){
System.out.println("请输入你需要打印多少阶的回形数:");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt(); // 接收num,则打印num阶的回形数
scan.close();
int[][] hui = new int[num][num];
for(int i = 0,j = 0,flag = 0,theNum = 1; theNum<=(num*num);) { // i可视为二维数组的第i+1排,j可视为二维数组的j+1列;flag表示回形数进行的第flag+1圈;theNum为赋的值。
if(j<num-flag) { //回形数向右走时
hui[i][j] = theNum;
j++;
theNum++;
}
else if(i+1<num-flag) { //回形数向下走时
hui[i+1][j-1] = theNum;
theNum++;
i++;
}
else {
for(int m = num-flag-1,n = num -flag-1;;) {
if(n>flag) { //回形数向左走时
n--;
hui[m][n] = theNum;
theNum++;
}
else if(m>flag+1) { //回形数向右走时
m--;
hui[m][n] = theNum;
theNum++;
}
else {
i = flag+1;
j = flag+1;
flag++;
break;
}
}
}
}
for(int a = 0;a<num;a++) {
for(int b = 0;b<num;b++) {
System.out.printf("%d ",hui[a][b]);
}
System.out.println("\n");
}
}
}
原文:https://www.cnblogs.com/Midnt/p/10841857.html