NYOJ852 蛇形填数(二)

原题链接


#include <stdio.h>
#include <string.h>
#define MAX 1001
int a[MAX][MAX];

int main(){
	int t, n, max, count, i, j;
	scanf("%d", &t);
	while(t--){
		scanf("%d", &n);
		max = (1 + n) * n / 2;
		count = 0;
		a[i = 1][j = 1] = ++count;
		while(count < max){
			//向右
			while(j < n - i + 1){
				if(a[i][j + 1] == 0)
					a[i][++j] = ++count;
				else break;
			}
			//向左下
			while(j > 1){
				if(a[i + 1][j - 1] == 0)
					a[++i][--j] = ++count;
				else break;
			}
			//向上
			while(i > 1){
				if(a[i - 1][j] == 0)
					a[--i][j] = ++count ;
				else break;
			}
		}
		//输出
		for(i = 1; i <= n; ++i){
			for(j = 1; j <= n - i + 1; ++j)
				printf("%d ", a[i][j]);
			printf("\n");
		}
		if(t) printf("\n");
		memset(a, 0, sizeof(a));
	}
	return 0;
}


posted on 2014-03-09 00:07  长木Qiu  阅读(159)  评论(0编辑  收藏  举报