旋转方阵
输入一个整数n(0 标准输出
输出一个n*n的旋转方阵,数字以顺时针方向逐渐增大,输出的每个整数宽度为4,且右对齐
范例输入
5
范例输出
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
这道题目是测试题,考试已经过去了,我抄下来后,实在想不出,想请大伙教教我。谢谢
#include <stdio.h> #include <stdlib.h> #define PV *(p + n * i + j) #define OVERODD *(p + (n/2) * n + (n/2)) = (n * n) - 1 #define SQUR val = right(*(prep+i), step_len, val, p) #define SQUD val = down(*(prep+i), step_len, val, p) #define SQUL val = left(*(prep+i), step_len, val, p) #define SQUU val = up(*(prep+i), step_len, val, p) #define SQU SQUR;SQUD;SQUL;SQUU; int n; void new_num(int, int *); int right(int, int, int, int *); int down(int, int, int, int *); int left(int, int, int, int *); int up(int, int, int, int *); void prt_num(int, int *); int main(void) { int i, num[1], *p_num, INITnum[4] = { 0, 1, 3, 2 }; p_num = (int *)num; L1: printf("请输入右内旋矩阵的基数: "); scanf("%d", &n); if (n <= 1) { printf("输入不合法..."); goto L1; } if (n == 2) { printf("\n"); for (i = 0; i < 4; i++) { printf("%4d ", INITnum[i]); if ((i + 1) % 2 == 0) { printf("\n"); } } printf("\n");; } if (n > 2) { p_num = malloc(n * n * sizeof(int)); new_num(n, p_num); prt_num(n, p_num); free(p_num); } return 0; } void new_num(int n, int *p) { int step_len = n - 1; int step_rep = (n - 1) / 2; int val = 0; int i; int rep[1], *prep; prep = rep; prep = malloc(step_rep * sizeof(int)); for (i = 0; i < step_rep; i++) { *(prep + i) = i; } if (n % 2 == 0 && n > 3) { i = 0; for (; step_rep > 0; step_rep--) { SQU i++; step_len--; } *(p + n * (n / 2 - 1) + n / 2 - 1) = n * n - 4; *(p + n * (n / 2 - 1) + n / 2) = n * n - 3; *(p + n * n / 2 + n / 2) = n * n - 2; *(p + n * n / 2 + n / 2 - 1) = n * n - 1; } else { i = 0; for (; step_rep > 0; step_rep--) { SQU i++; step_len--; } OVERODD; } free(prep); } int right(int rep, int len, int v, int *p) { int i = rep; int j = rep; for (; j < len; j++) { PV = v++; } return v; } int down(int rep, int len, int v, int *p) { int i = rep; int j = n - 1 - rep; for (; i < len; i++) { PV = v++; } return v; } int left(int rep, int len, int v, int *p) { int i = n - 1 - rep; int j = n - 1 - rep; for (; j > rep; j--) { PV = v++; } return v; } int up(int rep, int len, int v, int *p) { int i = n - 1 - rep; int j = rep; for (; i > rep; i--) { PV = v++; } return v; } void prt_num(int n, int *prt) { int i; printf("\n"); for (i = 0; i < n * n; i++) { printf("%4d ", *(prt + i)); if ((i + 1) % n == 0) { printf("\n"); } } printf("\n"); }