转载请注明出处:http://www.cnblogs.com/zhishoumuguinian/p/8395420.html
代码不好,请大神指导。
还是粘上代码吧,输出到屏幕太慢了,我输出到文件
1 #include <iostream> 2 #include <fstream> 3 #include <iomanip> 4 using namespace std; 5 int a[5][5]; 6 int flag[20]={0}; 7 int ans=0; 8 ofstream outfile("magic square.txt",ios::out); 9 bool Check(int x, int y) 10 { 11 if(x<3) 12 { 13 if(y<3) return true; 14 if(a[x][0]+a[x][1]+a[x][2]+a[x][3]==34) 15 return true; 16 return false; 17 } 18 else 19 { 20 if(y==0) 21 if((a[0][0]+a[1][0]+a[2][0]+a[3][0]!=34)||(a[0][3]+a[1][2]+a[2][1]+a[3][0]!=34)) return false; 22 if(y==1||y==2) 23 if(a[0][y]+a[1][y]+a[2][y]+a[3][y]!=34) return false; 24 if(y==3) 25 if((a[0][y]+a[1][y]+a[2][y]+a[3][y]!=34)||(a[0][0]+a[1][1]+a[2][2]+a[3][3])!=34) return false; 26 return true; 27 } 28 } 29 30 31 void dfs(int x, int y) 32 { 33 if(x==4) 34 { 35 ans++; 36 outfile<<"第"<<ans<<"个"<<endl; 37 for(int i=0; i<4; i++) 38 { 39 for(int j=0; j<4; j++) 40 { 41 outfile<<setw(2)<<a[i][j]<<" "; 42 } 43 outfile<<endl; 44 } 45 outfile<<endl<<endl; 46 return; 47 } 48 for(int num=1; num<=16; num++) 49 { 50 if(flag[num]==0) 51 { 52 a[x][y]=num; 53 flag[num]=1; 54 if(Check(x,y)) 55 { 56 if(y<3) dfs(x,y+1); 57 else dfs(x+1,0); 58 } 59 flag[num]=0; 60 } 61 } 62 63 64 } 65 66 int main() 67 { 68 dfs(0,0); 69 cout<<ans; 70 outfile.close(); 71 return 0; 72 }