/*
输出 n=5 的螺旋方阵
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
*/
class XDemo
{
public static void main(String[] args)
{
int SIZE = 5;
int i,j,k=0,n;
n = SIZE;
int[][] arr = new int[SIZE][SIZE];
for(i=0; i<n; i++)
{
//顶层,从左到右,行不变列变
for(j=i;j<=n-i-1;j++)
{
arr[i][j] = ++k;//输出1,2,3,4,5,17,18,19,25
}
//右边,从上到下,行变列不变
for (j=i+1; j<=n-i-1; j++)
{
arr[j][n-i-1] = ++k; //输出6,7,8,9,20,21
}
//底边,从右到左,行不变列变
for (j=n-i-2; j>=i; j--)
{
arr[n-i-1][j] = ++k; //输出10,11,12,13,22,23
}
//左边,从下到上,行变列不变
for (j=n-i-2; j>=i+1; j--)
{
arr[j][i] = ++k; //输出 14,15,16,24
}
}
for (i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
|