import java.util.*;
class LuoXuanFangZheng
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("请输入螺旋矩阵的规格:");
int n = input.nextInt();
int[][] arr =new int[n][n];
int counts=1;
int i=0;
int j=0;
int k=0;//每饶一圈 用k值加1
while(k<=n/2)
{
for(j=k;j<n-k-1;j++)//存入横向正序的数组
{
arr[i][j]=counts;
counts++;
}
// j+=k;
for(i=k;i<n-k-1;i++)//竖向正序数列
{
arr[i][j]=counts;
counts++;
}
//i-=k;
for(;j>k;j--)//横向反序的数组
{
arr[i][j]=counts;
counts++;
}
//j-=k;
for(;i>k;i--)//竖向反序数组
{
arr[i][j]=counts;
counts++;
}
k++;//满一圈K值加1
i++;//行号加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();
}
}
}
|
|