/* * 回形数 从键盘输入一个整数(1~20) ,则以该数字为矩阵的大小,把 1,2,3…n*n 的 数字按照顺时针螺旋的形式填入其中 */ /* * 一共重复上右下左四个循环的动作、这四个动作重复执行、 * 因此需要一个for循环里面四个for循环 * 第一个for循环执行n/2次 */
''''
import java.util.Scanner;
/*
* 回形数
从键盘输入一个整数(1~20) ,则以该数字为矩阵的大小,把 1,2,3…n*n 的
数字按照顺时针螺旋的形式填入其中
*/
/*
* 一共重复上右下左四个循环的动作、这四个动作重复执行、
* 因此需要一个for循环里面四个for循环
* 第一个for循环执行n/2次
*/
public class RectangleTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("please input the size of matrix:");
int size = scanner.nextInt();
int[][] rectangleMatrix = new int[size][size];
int count = 1;
scanner.close();
System.out.println(" rectangleMatrix.length:" + rectangleMatrix.length);
for (int i = 0; i < rectangleMatrix.length / 2; i++) {
// 横
for (int j = i; j < rectangleMatrix.length - i; j++) {
rectangleMatrix[i][j] = count++;
// count++;
}
// 右
for (int j = i + 1; j < rectangleMatrix.length - i - 1; j++) {
rectangleMatrix[j][rectangleMatrix.length - i-1] = count++;
// count++;
}
// 下
for (int j = rectangleMatrix.length - i - 1; j >= i; j--) {
rectangleMatrix[rectangleMatrix.length - i - 1][j] = count++;
}
// 左
for (int j = size - i - 2; j >= i + 1; j--) {
rectangleMatrix[j][i] = count++;
}
}
//如果是奇数行、则需要对中间数字单独赋值
if(count==size*size)
rectangleMatrix[size/2][size/2]=count;
for (int i = 0; i < rectangleMatrix.length; i++) {
for (int j = 0; j < rectangleMatrix.length; j++) {
System.out.print(rectangleMatrix[i][j] + "\t");
}
System.out.println();
}
}
}