class Luoxuan
{
public static void main (String[] args)
{
pintLuoxuan(8);
}
static void pintLuoxuan (int n)
{
int[][] arr = new int[n][n];
int flag = 1;
int value = 1;
int x1 = 0;
int y2 = n-1;
int x3 = n-1;
int y4 = 0;
for (int i = 0;i<n;i++) {
//flag 使区域1 2 和区域3 4交替执行
if (flag == 1) {
int y1 = x1;
for (int j = i;j < n;j++) {
arr[x1][y1] = value++;
y1++;
}
x1++;
int x2 = x1;
for (int k = i+1;k < n;k++) {
arr[x2][y2] = value++;
x2++;
}
y2--;
flag = 2;
} else if (flag == 2) {
int y3 = x3 - 1;
for (int a = i;a < n;a++) {
arr[x3][y3] = value++;
y3--;
}
x3--;
int x4 = x3;
for (int b = i+1;b < n;b++) {
arr[x4][y4] = value++;
x4--;
}
y4++;
flag = 1;
}
}
for (int x = 0;x < n;x++ )
{
for (int y = 0;y < n;y++ )
{
System.out.print(arr[x][y]+"\t");
}
System.out.println();
}
}
} |
|