描述 在nn方陈里填入1,2,…,nn,要求填成蛇形。例如n=4时方陈为: 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4
输入 直接输入方陈的维数,即n的值。(n<=100) 输出 输出结果是蛇形方陈。 样例输入 3 样例输出 7 8 1 6 9 2 5 4 3
package practice;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[][] a=new int[n][n];
int p=0;
int q=1;
int t=1;
for (int k = 1; k <= 2*n-1; k++) {
if(k%4==1) {
for (int i = p; i <= n-1-p; i++) {
a[i][n-1-p]=t++;
}
}else if(k%4==2) {
for (int i = n-1-q; i >= p; i--) {
a[n-1-p][i]=t++;
}
}else if(k%4==3) {
for (int i = n-1-q; i >= p; i--) {
a[i][p]=t++;
}
}else if(k%4==0) {
for (int i = q; i <= n-1-q; i++) {
a[p][i]=t++;
}
p++;q++;
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
|