原題鏈接
#include#include #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; }