蛇形

 Give you many positive integer N (N<=23), for each N, just output N*(N+1)/2 integers in a single line, separated by space. (Don't ask me why.) For each N, the output line contains integers from 1 to N, and each just once. Again, do not ask me why, thank you. I'm so busy. But I can tell you a secret, the output has relationship with number triangle. As:(N=3)

                   1

                   2   6

                   3   4   5

See the sample for more information.

输入

a positive integer N (N<=23). 

输出

For each N, output N*(N+1)/2 integers in a single line, separated by a blank space. 

样例输入

3 4 2 6

样例输出

1 2 6 3 4 5 1 2 9 3 10 8 4 5 6 7 1 2 3 1 2 15 3 16 14 4 17 21 13 5 18 19 20 12 6 7 8 9 10 11

#include <stdio.h>
int main(){
	int n,y,x;
	while (scanf("%d", &n) != EOF) {
		int a[23][23]={0},m=1;
		for(y=n;y>=1;y--){
		a[1][y]=m++;
	    }
	    for(x=2;x<=n;x++) {
		a[x][1]=m++;
	    }
	    x=x-1;
	    y=y+1;
	    while(m<=(n*(n+1)/2)){
		
		for(;x>=1 && y<=n;){
			if(a[--x][++y]==0){
			   a[x][y]=m++;
			}
			else{
				break;
			}
		}
		if (m > n*(n+1)/2) break;
        //下面的步骤是因为虽然break,x和y还是多加了一次,要注意。
		x = ++x;
		
		y=y-1; 
        //
		for(;y>=1;){    //for里面第一个数可以没有,不用其他的数字表示了。
			if(a[x][--y]==0){
				a[x][y]=m;
				m++; 
			} 
			else{
				break;
			}
		}
		if (m > n*(n+1)/2) break;
		y=y+1;
		for(;x<=n;){
			if(a[++x][y]==0){
				a[x][y]=m++;
			}
			else{
				break;
			}
		}
		if (m > n*(n+1)/2) break;
		    x=x-1;
	    } 
      for(y=n;y>=1;y--){
		for(x=1;x<=n-y+1;x++){
			if (y == 1 && x == n)
				printf("%d\n",a[x][y]);
			else
				printf("%d ",a[x][y]);
		}
	  }
	}
	
	
	return 0;
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值