Description
下面程序的功能是:输出n阶螺旋方阵。请将程序补充完整。
#include<stdio.h>
void Print(int [][30],int);
void Matrix(int [][30],int);
int main()
{
int a[30][30],n;
scanf("%d",&n);
Matrix(a,n);
Print(a,n);
return 0;
}
void Print(int a[][30],int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%4d",a[i][j]);
printf("\n");
}
}
//你提交的代码将放在这里
提交答案时,只需要提交自己补充的代码。
Input
一个正整数n(不超过30)。
Output
按照指定格式输出n阶螺旋方阵(每个整数采用%4d的格式输出)。
Sample Input 1
3
Sample Output 1
1 2 3 8 9 4 7 6 5
Hint
3阶螺旋方阵 4阶螺旋方阵 5阶螺旋方阵
1 2 3 1 2 3 4 1 2 3 4 5
8 9 4 12 13 14 5 16 17 18 19 6
7 6 5 11 16 15 6 15 24 25 20 7
10 9 8 7 14 23 22 21 8
13 12 11 10 9
我的代码:
void Matrix(int a[][30], int n) {
// Please fill this blank
int rownum = n;//用来对行数输出个数计数,即这一行输出多少个数字
int colnum = n - 1;//同理列数
int row=0, col=-1,t=1;//row,col代表下标,t代表数字总数
while (t <= n * n)
{
for (int i = 0; i < rownum; i++)//向右
a[row][++col] = t++;//使用++col可以有效避免特殊处理,使用col++列数超出了又需要col--
rownum--;//每一次排数之后都需要--,以下同理
for (int i = 0; i < colnum; i++)
a[++row][col] = t++;//使用++row可以避免多一次处理,比如这次是换下一行,需要row++,使用++row更简洁
colnum--;
for (int i = 0; i < rownum; i++)
a[row][--col] = t++;
rownum--;
for (int i = 0; i < colnum; i++)
a[--row][col] = t++;
colnum--;
}
}