不管是什么形状,这类题,每个元素的位置和值之间都存在着简单的映射关系。多观察,总结一下公式。
程序代码:
#include <stdio.h> int getValueOfIndex(int n, int row, int col) { int start, lap, offset, tmp; n--; lap = (row <= col) ? row : col; tmp = n - row - col; if(tmp < lap) lap = tmp; start = 3 * n * lap - 9 * lap * (lap - 1) / 2; tmp = n - 3 * lap; row -= lap; col -= lap; if(row == 0) offset = col; else if(col == 0) offset = tmp * 3 - row; else offset = tmp * 2 - col; return start + offset + 1; } int main() { int n, i, j; scanf("%d", &n); for(i = 0; i < n; i++) { for(j = 0; j < n - i; j++) printf("%-4d", getValueOfIndex(n, i, j)); printf("\n"); } return 0; }
重剑无锋,大巧不工