68 lines
1.3 KiB
C
68 lines
1.3 KiB
C
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#define MAX 15
|
||
|
||
int Square[MAX][MAX];
|
||
int N;
|
||
|
||
void printSquare() {
|
||
int i ,j;
|
||
for (i = 0; i < N; i++) {
|
||
for (j = 0; j < N; j++) {
|
||
printf("%d\t", Square[i][j]);
|
||
}
|
||
printf("\n");
|
||
}
|
||
}
|
||
|
||
int main() {
|
||
int row, col, num, i ,j;
|
||
|
||
do {
|
||
printf("\n請輸入奇數方陣大小 (1-15之間的奇數): ");
|
||
scanf("%d", &N);
|
||
|
||
if (N % 2 == 0 || N <= 0 || N > 15) {
|
||
printf("輸入錯誤:必須是1-15之間的奇數\n");
|
||
} else {
|
||
break;
|
||
}
|
||
} while (1);
|
||
|
||
// 初始化方陣
|
||
for (i = 0; i < N; i++) {
|
||
for (j = 0; j < N; j++) {
|
||
Square[i][j] = 0;
|
||
}
|
||
}
|
||
|
||
row = 0;
|
||
col = N / 2;
|
||
// printf("col=%d\n", col);
|
||
num = 1;
|
||
|
||
while (num <= N * N) {
|
||
Square[row][col] = num;
|
||
|
||
// 檢查下一個位置
|
||
int nextRow = (row - 1 + N) % N;
|
||
int nextCol = (col + 1) % N;
|
||
|
||
if (Square[nextRow][nextCol] != 0) {
|
||
// 如果下一個位置已被佔用,則往下移動
|
||
row = (row + 1) % N;
|
||
} else {
|
||
// 否則,移動到右上角的位置
|
||
row = nextRow;
|
||
col = nextCol;
|
||
}
|
||
|
||
num++;
|
||
}
|
||
|
||
printf("\n%d x %d 魔方陣:\n\n", N, N);
|
||
printSquare();
|
||
|
||
return 0;
|
||
}
|