如图,有这样的一个魔方,1放在第一行的中间位置,随后输入1~n²
放置要求:
1.下一个数字放在上一个数字的上一行右一列
2.若下一个数字被占了位置,则放在下一行
3.若到了右边界,那么到左边的第一列
4.若到了上边界,那么到最后一行
代码如下:
C语言:
#include <stdio.h>
int main() {
int a[10][10] = {0};
int n, i;
scanf("%d", &n);
int row = 0, col = (n - 1) / 2;
a[row][col] = 1;
for (i = 2; i <= n * n; i++) {
if (a[(row - 1 + n) % n][(col + 1) % n] == 0) {
row = (row - 1 + n) % n;
col = (col + 1 ) % n;
} else
row = (row + 1) % n;
a[row][col] = i;
}
for (row = 0; row < n; row++) {
for (col = 0; col < n; col++) {
printf("%d\t", a[row][col]);
}
printf("\n\n");
}
}
C++:
#include <iostream>
using namespace std;
int main() {
int a[10][10] = {0};
int n, i;
cin >> n;
int row = 0, col = (n - 1) / 2;
a[row][col] = 1;
for (i = 2; i <= n * n; i++) {
if (a[(row - 1 + n) % n][(col + 1) % n] == 0) {
row = (row - 1 + n) % n;
col = (col + 1 ) % n;
} else
row = (row + 1) % n;
a[row][col] = i;
}
for (row = 0; row < n; row++) {
for (col = 0; col < n; col++) {
cout << a[row][col] << "\t";
}
cout << endl << endl;
}
}