package com.yao.exer;
import java.util.Scanner;
/* 1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
*/
public class ArrayExer3 {
public static void main(String[] args) {
int j = 0;//列
int i = 0;//行
Scanner scan = new Scanner(System.in);
System.out.println("输入你想输入的数");
int len = scan.nextInt();
int[][] arr = new int[len][len];
int k = 0;
// k = 0 向右,k = 1向下,k = 2向左,k = 3向右
for(int m = 1;m <= len*len;m++) {//m个数
if(k == 0) {//向右
if(j < len && arr[i][j] == 0) {
arr[i][j++] = m;
}else {
k = 1;
i++;
j--;
m--;
continue;
}
}
if(k == 1) {//向下
if(i < len && arr[i][j] == 0) {
arr[i++][j] = m;
}else {
i--;
j--;
m--;
k = 2;
continue;
}
}
if(k == 2) {//向左
if(j>=0 && arr[i][j] == 0) {
arr[i][j--] = m;
}
else {
j++;
i--;
m--;
k = 3;
continue;
}
}
if(k == 3) {//向上
if(i >= 0 && arr[i][j] == 0) {
arr[i--][j] = m;
}else {
i++;
j++;
m--;
k = 0;
continue;
}
}
}
//遍历
for(int n = 0;n < len;n++) {
for(int r = 0;r < len;r++) {
System.out.print(arr[n][r]+"\t");
}
System.out.println();
}
}
}
回形数
最新推荐文章于 2022-07-31 09:40:23 发布