上三角问题

         题目描述:方阵的主对角线之上称为“上三角”。

请你设计一个用于填充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;
	}
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值