题目描述:方阵的主对角线之上称为“上三角”。
请你设计一个用于填充n阶方阵的上三角区域的程序。填充的规则是:使用1,2,3,。。。的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当n=3时,输出:
1 2 3
6 4
5
----题目出自 第二届全国软件专业人才设计与开发大赛 选拔赛
代码如下:
#include <stdio.h>
#include <conio.h>
#define MAX 30
//global variables
int map[MAX][MAX]={0};
int x=0,y=0;
int mode=1;
int max_num=0;
//prototype
void sum(int n);
void add();
void subtract();
int main()
{
int n;
int count=1;
printf("Please input the number:");
scanf("%d",&n);
sum(n);
while(true)
{
if(count>max_num)
break;
if(x>=n || y>=n || map[x][y]!=0)
{
subtract();
mode++;
count--;
if(mode>3)
mode=1;
}
map[x][y]=count++;
add();
}
for(int p=0;p<n;p++)
{
for(int q=0;q<n;q++)
{
if(map[p][q]!=0)
printf("%4d",map[p][q]);
}
printf("\n");
}
getch();
}
void sum(int n)
{
for(int i=1;i<=n;i++)
max_num+=i;
}
void add()
{
switch(mode)
{
case 1:
y++;
break;
case 2:
y--;x++;
break;
case 3:
x--;
break;
default:
break;
}
}
//Notice that this is a place that can be a mistake easily.
void subtract()
{
switch(mode)
{
case 1:
y--;
break;
case 2:
y++;x--;
break;
case 3:
x++;
break;
default:
break;
}
}