[Java] 纯文本查看 复制代码 public static void demo9() {
Scanner sc = new Scanner(System.in);
System.out.println("请选择方阵长度");
int end = sc.nextInt();
int start = 0;
//int end = 4;
int count = 0;
int[][] arr = new int[end][end];
//调用方法赋值
demo9_text(arr,start,end,count,end*end);
//打印二维数组
for(int i = 0 ; i < arr.length ; i ++) {
for(int j = 0 ; j < arr[i].length ; j ++) {
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
//五个参数,数组,本圈开始索引,本圈最大索引,要填写数字,最大(终止)数字
private static void demo9_text(int[][] arr,int start,int end,int count,int ends) {
//打印第一横行
for(int i = start ; i < end ; i ++) {
count ++;
arr[start][i] = count;
}
if(count == ends) {
return;
}
//右纵行
count --;
for(int i = start;i < end ; i ++) {
count++;
arr[i][end-1] = count;
}
//下横行
count--;
for(int i = end-1;i > start-1;i--) {
count ++;
arr[end-1][i] = count;
}
if(count == ends) {
return;
}
//左纵行
count --;
for(int i = end - 1 ; i >start;i --) {
count ++;
arr[i][start] = count;
}
demo9_text(arr,start + 1,end - 1,count,ends);
} |