八皇后问题
1 #include <bits/stdc++.h> 2 #define _for(i,a,b) for(int i = (a);i < (b);i ++) 3 using namespace std; 4 5 const int n = 8; 6 vector<vector<vector<int>>> rnt; 7 vector<vector<int>> C (n,vector<int> (n,0)); 8 9 int vis[3][39]; 10 11 void search(int cur) 12 { 13 if(cur==n) 14 rnt.push_back(C); 15 else 16 _for(i,0,n) 17 { 18 if(!vis[0][i] && !vis[1][cur+i] && !vis[2][i-cur+n]) 19 { 20 C[cur][i] = vis[0][i] = vis[1][cur+i] = vis[2][i-cur+n] = 1; 21 search(cur+1); 22 C[cur][i] = vis[0][i] = vis[1][cur+i] = vis[2][i-cur+n] = 0; 23 } 24 } 25 } 26 27 void print() 28 { 29 int kase = 1; 30 _for(i,0,rnt.size()) 31 { 32 cout << "Case:" << kase++ << endl; 33 _for(j,0,rnt[i].size()) 34 { 35 _for(k,0,rnt[i][j].size()) 36 { 37 if(rnt[i][j][k]) 38 cout << 'Q' << " "; 39 else 40 cout << '.' << " "; 41 } 42 cout << endl; 43 } 44 cout << endl << endl; 45 } 46 } 47 48 int main() 49 { 50 // freopen("output.txt","w",stdout); 51 memset(vis,0,sizeof(vis)); 52 search(0); 53 print(); 54 return 0; 55 }
vis[0]判列,vis[1]判主对角线,vis[2]判副对角线