花了一个半多小时,终于摆清楚了。
思路就是从右上往左下,从左下往右上,一条一条地赋值,注意边界的变化。
先输左上三角,无需讨论。然后针对n是奇数还是偶数,右下三角的赋值步骤稍有变化。
#include<stdio.h> int main(){ int n; scanf("%d", &n); int arr[100][100] = {0}; int i = 0, j = 0, k = 2; arr[0][0] = 1; int row = 0, col = 0; while(row<n && col<n){ row++, col++; if(row == n) break; i = 0, j = col; while(j >= 0) arr[i++][j--] = k++; row++, col++; if(row == n) break; i = row, j = 0; while(i >= 0) arr[i--][j++] = k++; } int up = 0, left = 0; if(n % 2 == 0){ while(up < n && left < n){ up++, left++; i = n-1, j = left; while(j < n) arr[i--][j++] = k++; up++, left++; i = up, j = n-1; while(i < n) arr[i++][j--] = k++; } } else if(n % 2 == 1){ while(up < n && left < n){ up++, left++; i = up, j = n-1; while(i < n) arr[i++][j--] = k++; up++, left++; i = n-1, j = left; while(j<n) arr[i--][j++] = k++; } } for(i = 0; i<n; i++){ for(j = 0; j<n; j++){ printf("%d ", arr[i][j]); } printf("\n"); } return 0; }