Advertisement
amstan

8 Queen Problem - Recursive Backtracking

Aug 18th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. //8 Queen Problem - Recursive Backtracking
  2. #include <bits/stdc++.h>
  3. #include <ext/pb_ds/assoc_container.hpp>
  4.  
  5. using namespace __gnu_pbds;
  6. using namespace std;
  7. typedef long long ll;
  8.  
  9. #define mem(dp,a)           memset(dp,a,sizeof dp)
  10. #define rep(i,a,b)          for(ll i=a;i<b;i++)
  11. #define pb(x)               push_back(x)
  12. #define mp(x,y)             make_pair(x,y)
  13. #define fastio              ios_base::sync_with_stdio(false);cin.tie(NULL)
  14. #define F                   first
  15. #define S                   second
  16. #define all(v)              (v).begin(),(v).end()
  17. #define pi                  3.14159265359
  18. ll INF=1e18+10;
  19. ll MOD=1000000007;
  20.  
  21. const int N=8;
  22. int row[N];
  23.  
  24. bool place(int r,int c)
  25. {
  26.     for(int prev=0;prev<c;prev++)
  27.       if(row[prev]==r || abs(row[prev]-r)==abs(prev-c))
  28.         return false;
  29.     return true;
  30. }
  31.  
  32. void backtrack(int c)
  33. {
  34.     if(c==8)
  35.     {
  36.         for(int i=0;i<8;i++)
  37.             cout<<row[i]<<" ";
  38.         cout<<"\n";
  39.     }
  40.     else
  41.     for(int r=0;r<8;r++)
  42.         if(place(r,c)){row[c]=r;backtrack(c+1);}
  43. }
  44.  
  45. int main()
  46. {
  47.     freopen("out.txt","w",stdout);
  48.     backtrack(0);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement