从键盘输入一个整数(1~20),则以该数字为矩阵,将数字按照顺时针螺旋填入其中
package array;
import java.util.Scanner;
/**
* @author 苗晓强
* @date 2023/7/26 23:56
* 回形数:
* 从键盘输入一个整数(1~20),则以该数字为矩阵,将数字按照顺时针螺旋填入其中
*/
public class RectangleTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个数字:");
int len = scanner.nextInt();
int [][] arrays = new int[len][len];
int s = len * len;
//k = 1 right 2 down 3 left 4 up
int k = 1;
int i = 0,j = 0;
for (int m = 1; m <= s; m++){
if (k == 1){
if (j < len && arrays[i][j] == 0){
arrays[i][j++] = m;
}else {
k = 2;
i++;
j--;
m--;
}
}else if (k == 2){
if (i < len && arrays[i][j] == 0){
arrays[i++][j] = m;
}else {
k = 3;
i--;
j--;
m--;
}
}else if (k == 3){
if (j >= 0 && arrays[i][j] == 0){
arrays[i][j--] = m;
}else {
k = 4;
i--;
j++;
m--;
}
}else if (k == 4){
if (i >= 0 && arrays[i][j] == 0){
arrays[i--][j] = m;
}else {
k = 1;
i++;
j++;
m--;
}
}
}
//遍历
for (int m = 0; m < arrays.length; m++){
for (int n = 0; n < arrays[m].length; n++){
System.out.print(arrays[m][n] + "\t");
}
System.out.println();
}
}
}