求奇偶阶幻方
奇:
#include <iostream> #include <cstring> using namespace std; int num[20][20]; void f(int x, int y, int n) { int x1, y1, i, j; /* for(i=0; i<n; ++i) { for(j=0; j<n; ++j) { printf("%4d", num[i][j]); } printf("\n"); } printf("\n\n");*/ if(num[x][y] == n*n) return; x1 = x - 1; y1 = y + 1; if(y1 >= n && x1 >= 0 && x1 < n) y1 = 0; else if(x1 < 0 && y1 >= 0 && y1 < n) x1 = n - 1; else if(x1 == -1 && y1 == n) x1 = 1, y1 = n-1; else if(num[x1][y1] != 0) x1 = x+1, y1 = y; num[x1][y1] = num[x][y] + 1; f(x1, y1, n); } void solve(int n) { int x, y, x1, y1, i, j; memset(num, 0, sizeof(num)); num[0][n/2] = 1; num[n-1][n/2] = n * n; num[n-1][n/2+1] = 2; x = n-1; y = n/2 + 1; f(x, y, n); for(i=0; i<n; ++i) { for(j=0; j<n; ++j) { printf("%4d", num[i][j]); } printf("\n"); } } int main() { // freopen("c:/aaa.txt", "r", stdin); int n, T; scanf("%d", &T); while(T --) { scanf("%d", &n); solve(n); } return 0; }
另外求偶数阶幻方:(网上找的代码)
#include<iostream> #include<iomanip> using namespace std; #define max 179 int a[max][max];//幻方的格 int k, i, j; int n;//幻方的阶 int sum;//每行的和 void check() { int temp1, temp2; //row and column check for( i = 1 ; i <= n; i ++ ) { temp1 = 0; temp2 = 0; for( j = 1 ; j <= n; j ++ ) { temp1 += a[i][j]; temp2 += a[j][i]; } if( temp1 != sum || temp2 != sum ) { cout<<"check error"<<endl; return; } } //cross check temp1 = 0; temp2 = 0; for( i = 1 ; i <= n; i ++ ) { temp1 += a[i][i]; temp2 += a[i][n-i+1]; } if( temp1 != sum || temp2 != sum ) { cout<<"check error"<<endl; return; } cout<<"check passed"<<endl; } void swap( int & a , int & b ) { int t; t = a; a = b; b = t; } int main() { while(1) { cout<<"input the order of magic(even) n = "; cin>>n; if( n % 2 == 1 ) { cout<<"input error"<<endl; continue; } sum = n*(n*n+1)/2; cout<<"sum of a line: "<<sum<<endl; for( i = 1 ; i <= n ; i ++ ) { for( j = 1 ; j <= n ; j ++ ) { a[i][j] = (i - 1) * n + j; } } k = n / 4; if( n == 4 * k ) // n是4的倍数 { for( i = k + 1 ; i <= 3 * k ; i ++ ) { for( j = 1 ; j <= k ; j ++ ) { swap(a[i][j],a[n+1-i][n+1-j]); swap(a[j][i],a[n+1-j][n+1-i]); } } } else // n = 4 * k + 2 { for( i = 1 ; i <= 2 * k + 1; i ++ ) { swap(a[i][i],a[n+1-i][n+1-i]); swap(a[i][n+1-i],a[n+1-i][i]); } for( i = 1 ; i <= k + 2 ; i ++ ) { for( j = k + 3 ; j <= 3 * k ; j ++ ) { swap(a[i][j],a[n+1-i][j]); swap(a[j][i],a[j][n+1-i]); } } for( i = k + 3 ; i <= 2 * k + 1 ; i ++ ) { for( j = 1 ; j <= k - 1 ; j ++ ) { swap(a[i][j],a[n+1-i][j]); swap(a[i][n+1-j],a[n+1-i][n+1-j]); swap(a[j][i],a[j][n+1-i]); swap(a[n+1-j][i],a[n+1-j][n+1-i]); } } for( i = 1 ; i <= k * 2 + 1 ; i ++ ) { if( i == 1 ) j = k + 2; else j = i - 1; swap(a[i][j],a[n+1-i][j]); swap(a[j][i],a[j][n+1-i]); } } //output for( i = 1 ; i <= n ; i ++ ) { for( j = 1 ; j <= n ; j ++ ) { cout<<setw(4)<<a[i][j]; } cout<<endl; } check();//检查是否满足幻方条件 } return 0; }