Advertisement
kokokozhina

8_ferzes

Sep 5th, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <set>
  4.  
  5. using namespace std;
  6.  
  7. int cnt = 0;
  8.  
  9. class Queen{
  10. public:
  11.     int col, row;
  12.     Queen* nb;
  13.     bool canAttack(int Col, int Row);
  14.     bool advance();
  15.     Queen(int Col, Queen* Nb){
  16.         col = Col;
  17.         nb = Nb;
  18.         row = 1;
  19.     }
  20.     ~Queen(){
  21.         if(nb)
  22.             delete nb;
  23.     }
  24.     bool findSolution();
  25.     void print();
  26. };
  27.  
  28. bool Queen::canAttack(int Col, int Row){
  29.     if(Row == row)
  30.         return true;
  31.     if(abs(Row - row) == abs(Col - col))
  32.         return true;
  33.     if(nb)
  34.         return nb->canAttack(Col, Row);
  35.     return false;
  36. }
  37.  
  38. bool Queen::advance(){
  39.     if(row < 8){
  40.         row++;
  41.         return this->findSolution();
  42.     }
  43.     if(!nb)
  44.         return false;
  45.     if(nb->advance()){
  46.         row = 1;
  47.         return this->findSolution();
  48.     }
  49.     return false;
  50. }
  51.  
  52. bool Queen::findSolution(){
  53.     if(!nb)
  54.         return true;
  55.     while(nb->canAttack(col, row))
  56.         if(!this->advance())
  57.             return false;
  58.     return true;
  59. }
  60.  
  61. void Queen::print(){
  62.     if(this->findSolution()){
  63.         cnt++;
  64.     }
  65. }
  66.  
  67. int main(){
  68.     Queen* lastQueen = NULL;
  69.     set<Queen*> s;
  70.     for(int i = 1; i < 9; i++){
  71.         lastQueen = new Queen(i, lastQueen);
  72.         lastQueen->findSolution();
  73.     }
  74.     while(lastQueen->findSolution()){
  75.         lastQueen->print();
  76.         lastQueen->advance();
  77.     }
  78.     cout << cnt << endl;
  79.     delete lastQueen;
  80.     system("pause");
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement