# 回形数格式方阵的实现

1 2
4 3

## 方法1：

import java.util.Scanner;

public class RectangleTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("输入一个数字");
int len = in.nextInt();
int[][] arr = new int[len][len];

int s = len * len;
int k = 1;
int i = 0, j = 0;
for (int m = 1; m <= s; m++) //m从1开始放入s个
{
if (k == 1)
{
if (j < len && arr[i][j] == 0)
arr[i][j++] = m;
else
{
k = 2;//换方向
i++;//i这一行已经放了，所以到下一行
j--;//j = len 是跳出的，所以j回退一个
m--;//m也回退一个
}
}
else if (k == 2)
{
if (i < len && arr[i][j] == 0)
arr[i++][j] = m;
else
{
k = 3;
i--;
j--;
m--;
}
}
else if (k == 3)
{
if (j >= 0 && arr[i][j] == 0)
arr[i][j--] = m;
else
{
k = 4;
i--;
j++;
m--;
}

}
else if (k == 4)
{
if (i >= 0 && arr[i][j] == 0)
arr[i--][j] = m;
else
{
k = 1;
i++;
j++;
m--;
}
}
}
for (int[] row : arr)
{
for (int odd : row)
System.out.printf("%4d", odd);
System.out.println();
}
}
}


## 方法2：

import java.util.Scanner;

public class RetangleTest2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] arr = new int[n][n];

int count = 0;//要填入的数字
int maxX = n - 1;//x轴的最大下标
int maxY = n - 1;//y轴的最大下标
int minX = 0;//x轴的最小下标
int minY = 0;//y轴的最大下标
while (minX <= maxX) //也可以写成minY <= maxY
{
for (int x = minX; x <= maxX; x++)
{
arr[minY][x] = ++count;
}
minY++;
for (int y = minY; y <= maxY; y++)
{
arr[y][maxX] = ++count;
}
maxX--;
for (int x = maxX; x >= minX; x--)
{
arr[maxY][x] = ++count;
}
maxY--;
for (int y = maxY; y >= minY; y--)
{
arr[y][minX] = ++count;
}
minX++;
}
for (int m = 0; m < arr.length; m++)
{
for (int j = 0; j < arr[m].length; j++)
System.out.printf(arr[m][j] + "\t");
System.out.println();
}
}
}


11-23 6421
10-03

09-14
09-14
04-28 1138
07-27 936
12-04 319
11-12 726