奇数幻方

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int INF=0x3f3f3f3f;
 5 const int base=131;
 6 const int mod=1e9+7;
 7 const int Maxn=1e6+5;
 8 int n,sx,sy;
 9 bool flag=true; 
10 int a[15][15];
11 
12 void print(){
13     for(int i=1;i<=n;i++){
14         for(int j=1;j<=n;j++){
15             printf("%d ",a[i][j]);
16         }
17         printf("\n");
18     }
19 }
20 
21 void dfs(int x,int y,int k){
22     //cout<<"xy:"<<x<<" "<<y<<endl;
23     //cout<<"k:"<<k<<endl;
24     if(k==n*n+1 && flag){
25         print();
26         flag=false;
27         return;
28     }
29     int dx=x-1,dy=y-1;
30     if(dx>0 && dy>0 && a[dx][dy]==0){
31         a[dx][dy]=k;
32         dfs(dx,dy,k+1);
33     }
34     else if(a[dx][dy]!=0){
35         a[x+1][y]=k;
36         dfs(x+1,y,k+1);
37     }
38     else if(dx<=0 && dy<=0){
39         a[x+1][y]=k;
40         dfs(x+1,y,k+1);
41     }
42     else if(dx<=0 && dy>0){
43         a[n][dy]=k;
44         dfs(n,dy,k+1);    
45     }
46     else if(dy<=0 && dx>0){
47         a[dx][n]=k;
48         dfs(dx,n,k+1); 
49     }
50     
51 }
52 
53 int main(){
54     scanf("%d",&n);
55     a[1][n/2+1]=1;
56     sx=1;sy=n/2+1;
57     dfs(sx,sy,2);
58     return 0;
59 }

 

posted @ 2019-07-20 22:00  pengcheng_official  阅读(194)  评论(0编辑  收藏  举报