// 输出魔方阵 voidprintMagicSquare(int m, int** magicSquare) { printf("魔方阵行数 m = %d:\n", m); for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { printf("%2d ", magicSquare[i][j]); } printf("\n"); } }
// 构建魔方阵 voidgenerateMagicSquare(int m) { if (m % 2 == 0) { printf("错误: m 必须是奇数。\n"); return; }
// 动态分配内存来存储魔方阵 int** magicSquare = (int**)malloc(m * sizeof(int*)); for (int i = 0; i < m; i++) { magicSquare[i] = (int*)malloc(m * sizeof(int)); }
// 初始化魔方阵的所有元素为 0 for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { magicSquare[i][j] = 0; } }
int num = 1; int row = 0; int col = m / 2;
while (num <= m * m) { magicSquare[row][col] = num; num++;
// 计算下一个位置 int nextRow = (row - 1 + m) % m; int nextCol = (col + 1) % m;
// 如果下一个位置已经被占据,则向下移动一行 if (magicSquare[nextRow][nextCol] != 0) { row = (row + 1) % m; } else { row = nextRow; col = nextCol; } }
printMagicSquare(m, magicSquare);
// 释放动态分配的内存 for (int i = 0; i < m; i++) { free(magicSquare[i]); } free(magicSquare); }