-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSquare.cpp
More file actions
144 lines (138 loc) · 2.56 KB
/
Square.cpp
File metadata and controls
144 lines (138 loc) · 2.56 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
//n阶幻方求解
#include<iostream>
using namespace std;
void OddSquare(int **a,int n);
void DEvenSquare(int **a,int n);
void SEvenSquare(int **a,int n);
int main()
{
int n;
cout << "请输入幻方阶数:";
while(cin >> n){
//分配n个int*内存+n*n个int内存
int **a = new int*[n];
for(int i = 0; i < n; ++i){
a[i] = new int[n]();
}
switch(n%4){
case 0:
DEvenSquare(a,n);
break;
case 1:
case 3:
OddSquare(a,n);
break;
case 2:
SEvenSquare(a,n);
break;
}
int *colSum = new int[n+1]();
int rowSum;
for(int i = 0; i < n; ++i){
rowSum = 0;
for(int j = 0; j < n; ++j)
{
rowSum += a[i][j];
cout << a[i][j] << " ";
colSum[j] += a[i][j];
if(i == j)
colSum[n] += a[i][j];
}
cout << " ";
cout << rowSum;
cout << endl;
}
cout << endl;
for(int i = 0; i < n+1; ++i)
cout << colSum[i] << " ";
cout << endl;
//释放n*n个int内存+n个int*内存
for(int i = 0; i < n; ++i){
delete []a[i];
}
delete []a;
delete []colSum;
cout << "请输入幻方阶数:";
}
return 0;
}
//单偶阶幻方n=4k+2
void SEvenSquare(int **a,int n)
{
int k = n/2;
int row = 0;
int col = k/2;
for(int i = 1; i <= k*k; ++i){
a[row][col] = i;
a[row][col+k] = i + 2*k*k;
a[row+k][col] = i + 3*k*k;
a[row+k][col+k] = i + k*k;
int rowt = row;
int colt = col;
row = (row - 1 + k) % k;
col = (col - 1 + k) % k;
if(a[row][col] > 0){
row = (rowt + 1) % k;
col = colt;
}
}
int m = k/2;
int t = (n - 2) / 4;
for(int i = 0; i < k; ++i){
int j;
if(i == m){//等于中间行
for(j = m; j < m+t; ++j){
int temp = a[i][j];
a[i][j] = a[i+k][j];
a[i+k][j] = temp;
}
for(j = m+k; j >m+k-t+1; --j){
int temp = a[i][j];
a[i][j] = a[i+k][j];
a[i+k][j] = temp;
}
}
else{
for(j = 0; j < t; ++j){
int temp = a[i][j];
a[i][j] = a[i+k][j];
a[i+k][j] = temp;
}
for(j = m+k; j >m+k-t+1; --j){
int temp = a[i][j];
a[i][j] = a[i+k][j];
a[i+k][j] = temp;
}
}
}
}
//双偶阶幻方 n=4k
void DEvenSquare(int **a,int n)
{
int k = 1;
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
{
if(i%4 == j%4 || i%4+j%4==3)
a[i][j] = n*n + 1 - k++;//置为互补数
else
a[i][j] = k++;
}
}
//奇数阶幻方
void OddSquare(int **a,int n)
{
int row = 0;
int col = n/2;
for(int i = 1; i <= n*n; ++i){
a[row][col] = i;
int rowt = row;
int colt = col;
row = (row - 1 + n) % n;
col = (col - 1 + n) % n;
if(a[row][col] > 0){
row = (rowt + 1) % n;
col = colt;
}
}
}