标签:
c语言上机。。。。
c写的幻方。
1 /************************************************************************* 2 > File Name: code/class/7.c 3 > Author: 111qqz 4 > Email: rkz2013@126.com 5 > Created Time: 2015年11月11日 星期三 19时31分50秒 6 ************************************************************************/ 7 8 #include<stdio.h> 9 #include <string.h> 10 11 int n; 12 int a[105][105]; 13 14 15 void swap(int *a,int *b) 16 { 17 int tmp; 18 tmp = *a; 19 *a = *b; 20 *b = tmp; 21 } 22 int fix_x( int x,int k,int n) 23 { 24 if (k%2==1) 25 { 26 if (x==0) 27 return n; 28 else return x; 29 } 30 else 31 { 32 if (x==n) 33 return n+n; 34 else return x; 35 } 36 } 37 int fix_y ( int y,int k,int n) 38 { 39 if (k<3) 40 { 41 if (y==n+1) 42 return 1; 43 else return y; 44 } 45 else 46 { 47 if (y==2*n+1) 48 return n+1; 49 else return y; 50 } 51 // if (y==n+1) 52 // return 1; 53 // else return y; 54 } 55 void print() 56 { 57 for ( int i = 1 ; i <= n ; i++) 58 { 59 for ( int j = 1 ; j <= n ; j++) 60 printf("%d ",a[i][j]); 61 62 printf("\n"); 63 } 64 65 } 66 67 void OddMagic(int n,int x,int y,int k) //k表示4中状态。。。。 68 { 69 70 int cur ; 71 if (k==1) cur = 1; 72 if (k==4) cur = n*n+1; 73 if (k==3) cur = n*n*2+1; 74 if (k==2) cur = n*n*3+1; 75 int cnt = 1; 76 while (cnt<=n*n) 77 { 78 a[x][y]=cur; 79 int prex = x; 80 int prey = y; 81 cur++; 82 cnt++; 83 x--; 84 y++; 85 x = fix_x(x,k,n); 86 y = fix_y(y,k,n); 87 if (a[x][y]) 88 { 89 x = prex+1; 90 y = prey; 91 } 92 93 } 94 95 } 96 int main() 97 { 98 memset(a,sizeof(a),0); 99 scanf("%d",&n); 100 if (n%2==1) 101 { 102 int x = 1; 103 int y = n/2+1; 104 OddMagic(n,x,y,1); 105 } 106 else 107 { 108 if (n%4==0) 109 { 110 for ( int i = 1,num=1 ; i <= n ; i++) 111 for ( int j = 1 ; j <= n ; j++,num++) 112 a[i][j]=num; 113 114 115 for ( int i = 1 ; i <= n ; i++) 116 { 117 for ( int j = 1 ; j <= n ; j++) 118 { 119 if (i==j||i+j>=n+1) continue; 120 int tmp; 121 tmp = a[i][j]; 122 a[i][j] = a[n+1-i][n+1-j]; 123 a[n+1-i][n+1-j] = tmp; 124 } 125 } 126 } 127 else 128 { 129 int x = 1; 130 int y = n/4+1; 131 int hn = n/2; 132 133 OddMagic(hn,x,y,1); 134 OddMagic(hn,x+hn,y,2); 135 OddMagic(hn,x,y+hn,3); 136 OddMagic(hn,x+hn,y+hn,4); 137 138 int m = n/4; 139 for ( int i = 1 ; i <= hn ;i++) 140 { 141 for ( int j = 1 ; j <= m ; j++) 142 { 143 int tmp; 144 if (i==m+1&&j==m) 145 { 146 tmp = a[m+1][m+1]; 147 a[m+1][m+1] = a[m+1+hn][m+1]; 148 a[m+1+hn][m+1] = tmp; 149 continue; 150 151 } 152 tmp = a[i][j]; 153 a[i][j] = a[i+hn][j]; 154 a[i+hn][j] = tmp; 155 // swap(a[i][j],a[i+n][j]); 156 } 157 } 158 159 for ( int i = 1 ; i <= hn ; i++) 160 { 161 for ( int j = n ; j>=n-m+2 ; j--) 162 { 163 int tmp; 164 tmp = a[i][j]; 165 a[i][j] = a[i+hn][j]; 166 a[i+hn][j] = tmp; 167 } 168 } 169 170 171 172 173 } 174 } 175 print(); 176 177 }
标签:
原文地址:http://www.cnblogs.com/111qqz/p/4957327.html