填充三角形
例如输入 3输出 1 2 3
6 4
5
输入 4
输出 1 2 3 4
9 10 5
8 6
7
int i,j,k=0,s=0,n,a[100][100]; scanf("%d",&n); for(i=0;i<n;i++) for(j=0;j<n;j++) a[i][j]=0; while(k<n/2) {for(i=k,j=k;j<n-k;j++) if(!a[i][j]) a[i][j]=++s; for(i=k,j=n-2*k-1;i<n-k;i++,j--) if(!a[i][j]) a[i][j]=++s; for(i=n-k-1,j=k;i>k;i--) if(!a[i][j]) a[i][j]=++s; k++;} for(i=0;i<n;i++) {for(j=0;j<n;j++) if(a[i][j]) printf("%-5d",a[i][j]); printf("\n");}
#include <stdio.h> #include <math.h> #define MAX_SIZE 20 static void triangle(int n, int r, int c, int count, int (* t)[MAX_SIZE]) { int i = r, j = c; if(n < 2) { if(n == 1) t[r][c] =count++; return; } while(j < c + n - 1) t[r][j++] = count++; while(i < r + n - 1) t[i++][j--] = count++; while(i > r) t[i--][c] = count++; triangle(n - 3, r + 1, c + 1, count, t); } static int sum(int n) { int s = 0; while(n) s += n--; return s; } int main(void) { int n, w, i, j, t[MAX_SIZE][MAX_SIZE] = {0}; char format[5] = "%-xd"; scanf("%d", &n); w = (int)log10(sum(n)) + 2; format[2] = w + '0'; triangle(n, 0, 0, 1, t); for(i = 0; i < n; i++) { for(j = 0; j < n; j++) t[i][j] && printf(format, t[i][j]); printf("\n"); } return 0; }