import java.util.Scanner;
public class LuoXuan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();//键盘录入螺旋方阵的维度
int[][] arr = new int[n][n];//定义一个二维数组存储螺旋变化的值
int up = 0;//定义一个上边的指针
int down = n - 1;//定义一个底边的指针
int left = 0;//定义一个左边的指针
int right = n - 1;//定义一个右边的指针
int x = 0;//定义一个螺旋变化的变量,初始值为0
while (x!=n*n) {
while (left <= right)// 顶边,从左到右,行不变列变
{
arr[up][left] = ++x;
left++;
}
up++;
left = up - 1;
while (up <= down)// 右边,从上到下,行变列不变
{
arr[up][right] = ++x;
up++;
}
right--;
up = left + 1;
while (left <= right)// 底边,从右到左,行不变列变
{
arr[down][right] = ++x;
right--;
}
down--;
right = down;
while (up <= down)//左边,从下到上,行变列不变
{
arr[down][left] = ++x;
down--;
}
left++;
down = right;
}
for (int z = 0; z < arr.length; z++) {//打印二维数组
for (int y = 0; y < arr[z].length; y++) {
System.out.print(arr[z][y] + "\t");
}
System.out.println();
}
}
} |
|