神奇的幻方

原题链接:https://www.luogu.org/problem/show?pid=2615#sub

题目要求我们生成这个幻方,那么我们只需要模拟一下这个幻方的形成过程就好,非常简单的一道模拟。

AC代码:

 1 #include<iostream>
 2 #define maxn 41
 3 #define check cout << "ok" << endl;
 4 using namespace std;
 5 int a[maxn][maxn];
 6 int n;
 7 int get_hf_line(int x){
 8     int ans = -1;
 9     for (int i=1;i<=n;i++)
10         for (int j=1;j<=n;j++){
11             if (a[i][j] == x)
12                 ans = i;
13         }
14     return ans;
15 }
16 
17 int get_hf_column(int x){
18     int ans = -1;
19     for (int i=1;i<=n;i++)
20         for (int j=1;j<=n;j++)
21             if (a[i][j] == x)
22                 ans = j;
23     return ans;
24 }
25 
26 
27 int main(){
28     cin >> n;
29     int mid = n/2 + 1; 
30     a[1][mid] = 1;
31     for (int k=2;k<=n*n;k++){
32         int kx = get_hf_line(k-1);
33         int ky = get_hf_column(k-1);
34 
35         //judge
36         if (kx == 1 && ky != n)
37             a[n][ky+1] = k;
38 
39         if (ky == n && kx !=1)
40             a[kx-1][1] = k;
41 
42         if (a[1][n] == k-1)
43             a[2][n] = k;
44 
45         if (kx != 1 && ky != n){
46             if (a[kx-1][ky+1] == 0)
47                 a[kx-1][ky+1] = k;
48             else
49                 a[kx+1][ky] = k;
50         }
51     }
52     for (int i=1;i<=n;i++){
53         for (int j=1;j<=n;j++)
54             printf("%d ",a[i][j]);
55         cout << endl;
56     }
57     return 0;
58 }

 

posted @ 2017-08-29 17:16  ShawnZhou_Aether  阅读(226)  评论(0编辑  收藏  举报