了解幻方
1 #include <iostream>
2 #include <vector>
3 #include <iomanip>
4
5 using namespace std;
6
7 int main()
8 {
9 int num;
10 cout << "请输入幻方的阶数: ";
11 cin >> num;
12
13 if (num <= 2)
14 {
15 cout <<"2以下的阶没有幻方!" << endl;
16 exit(0);
17 }
18
19 vector<vector<int> > MS(num);
20 for (int i = 0; i != MS.size(); ++i)
21 MS[i].resize(num);
22
23 for (int i = 0; i != MS.size(); ++i)
24 for (int j = 0; j != MS[i].size(); ++j)
25 MS[i][j] = 0;
26
27 int total = num * num;
28 MS[0][num / 2] = 1;
29 int p = 0;
30 int q = num / 2;
31 for (int i = 2; i <= total; ++i)
32 {
33 if (0 == p && (num - 1) == q)
34 {
35 MS[p + 1][q] = i;
36 ++p;
37 continue;
38 }
39
40 if (p != 0 && q != (num - 1) && MS[p - 1][q + 1] != 0)
41 {
42 MS[p + 1][q] = i;
43 ++p;
44 }
45 else if ( 0 == p && q < num - 1)
46 {
47 MS[num - 1][q + 1] = i;
48 p = num - 1;
49 ++q;
50 }
51 else if (p > 0 && (num - 1) == q)
52 {
53 MS[p - 1][0] = i;
54 --p;
55 q = 0;
56 }
57 else if (p > 0 && q < num - 1)
58 {
59 MS[p - 1][q + 1] = i;
60 --p;
61 ++q;
62 }
63 else
64 cout << "Error!" << endl;
65 }
66
67 for (int i = 0; i != MS.size(); ++i)
68 {
69 for (int j = 0; j != MS[i].size(); ++j)
70 cout << setw(3) << MS[i][j] << " ";
71
72 cout << endl;
73 }
74
75 return 0;
76 }
posted on 2009-08-26 23:04
diwayou 阅读(1471)
评论(1) 编辑 收藏 引用 所属分类:
数学