魔方阵(MagicsSquare)

魔方阵是一个古老的智力问题,它要求在一个 N * N 的方阵中填入 1~N²的数字( N 要求为奇数),使得每一行、每一列、每条对角线的累加和都相等。

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 
 5 int** MagicsSquare(int M);
 6 void PrintMagicsSquare(int** MS, int M);
 7 
 8 int main(void)
 9 {
10     int M;
11     int** MS;
12 
13     do
14     {
15         printf("请输入要生成的魔方阵的阶数(奇数阶):\n");
16         scanf(" %d", &M);
17     } while (M % 2 == 0);
18 
19     MS = MagicsSquare(M);
20 
21     PrintMagicsSquare(MS, M);
22 
23     system("pause");
24     return 0;
25 }
26 
27 int** MagicsSquare(int M)
28 {
29     int i;
30     int x;//列坐标
31     int y;//行坐标
32     int** MS = NULL;
33 
34     MS = (int**)calloc(M, sizeof(int*));//创建动态二维数组
35     for (i = 0; i < M; i++)
36     {
37         MS[i] = (int*)calloc(M, sizeof(int));
38     }
39 
40     x = M / 2;
41     y = 0;
42     MS[y][x] = 1;
43     for (i = 2; i <= M * M; i++)
44     {
45         y = (y - 1 + M) % M;
46         x = (x - 1 + M) % M;
47 
48         if (MS[y][x] != 0)
49         {
50             y = (y + 2 + M) % M;
51             x = (x + 1 + M) % M;
52         }
53         MS[y][x] = i;
54     }
55     return MS;
56 }
57 
58 void PrintMagicsSquare(int** MS, int M)
59 {
60     int i;
61     int j;
62     for (i = 0; i < M; i++)
63     {
64         for (j = 0; j < M; j++)
65         {
66             printf("%4d", MS[i][j]);
67         }
68         printf("\n");
69     }
70 }

 

posted @ 2022-01-03 23:29  吕辉  阅读(285)  评论(0)    收藏  举报