Data_Structure/作業/unit2/test.c
2025-01-20 21:30:53 +08:00

68 lines
1.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}