n阶奇数魔方阵问题

#n阶奇数魔方阵基本描述:
分析的文章的链接

贴实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
void DisplayMatrix(int *A, int n);
int main()
{
int *A;
int n;
while (cin >> n)
{
A = new int[n*n];
memset(A, 0, n*n * sizeof(int));
int row, col;
row = 0; col = (n - 1) / 2;
A[row*n + col] = 1;
for (int k = 2; k <= n*n; k++)
{
row--;
col++;
if (row < 0) row += n;
if (col >= n) col -= n;
while (A[row*n + col] != 0)
{
row += 2; col--;
if (row >= n) row -= n;
if (col < 0) col += n;
}
A[row*n + col] = k;
}
DisplayMatrix(A, n);
delete[] A;
}
}
void DisplayMatrix(int *A, int n)
{
for (int row = 0; row < n; ++row) {
for (int col = 0; col < n; ++col) {
cout.width(5);
cout << A[row*n + col];
}
cout << endl;
}
}
文章目录
|