1. 程式人生 > >蛇形填數 (二)

蛇形填數 (二)

蛇形填數(二)

時間限制:2000 ms  |  記憶體限制:65535 KB 難度:3
描述
1  2  3  4  5
12 13 14 6
11 15 7
10 8
9
跟蛇形填數一樣,只是填數要求按照三角形填。注意每組資料之間用空行隔開
輸入
第一行有一個N,表示N組測試資料
接下來每組資料包括一個數字X,表示三角形的邊長,0< X <1000
輸出
輸出之後填好之後的圖
樣例輸入
2
5
4
樣例輸出
1  2  3  4  5
12 13 14 6
11 15 7
10 8
9

1  2  3  4
9  10 5
8  6
7
#include<iostream>
#include<string.h>
using namespace std;
#define MAX 1000
int a[MAX][MAX];
int main(void){
	int n,x,y,s,count;
	cin>>s;
	while(s--){
		cin>>n;
		memset(a,0,sizeof(a));
		count=a[x=0][y=0]=1;
		while(count<n*(n+1)/2){
			while(y+1<n&&!a[x][y+1])a[x][++y]=++count;
			while(x+1<n&&!a[x+1][y-1])a[++x][--y]=++count;
			while(x-1>=0&&!a[x-1][y])a[--x][y]=++count;
		}
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n-i;j++)
			cout<<a[i][j]<<" ";
			cout<<endl;
		}
		cout<<endl;
	}
}