dipankar_kumar_singh

N Queen

Nov 20th, 2022
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | Software | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std ;
  3.  
  4. vector<int> queen ;
  5. int n = 4 ;
  6.  
  7. bool check(int level, int col)
  8. {
  9.     for (int i = 0; i < level; i++)
  10.     {
  11.         int queenCol = queen[i];
  12.         int queenRow = i;
  13.  
  14.         if ((col == queenCol) or (abs(level - queenRow) == abs(col - queenCol)))
  15.         {
  16.             return false;
  17.         }
  18.     }
  19.     return true;
  20. }
  21.  
  22. void printsolution()
  23. {
  24.     for(int i = 0 ; i < n ; i++){
  25.         for(int j = 0 ; j < n ; j++)
  26.             cout << (queen[i] == j) << ' ';
  27.         cout << endl ;
  28.     }
  29.     cout << endl << endl;
  30. }
  31.  
  32. int solve(int level)
  33. {
  34.     if(level == n)
  35.     {
  36.         // because we Have to Place 8 Queen [ NO OTHER CHOICE LEFT ] //
  37.         // thus we must reach level == n ; thus returning 1 as -> ture --> possible
  38.        
  39.         printsolution();
  40.         return 1 ;
  41.     }
  42.  
  43.     int ans = 0 ;
  44.  
  45.     for(int c = 0 ; c < n ; c++)
  46.     {
  47.         if(check(level,c))
  48.         {
  49.             // place
  50.             queen[level] = c ;
  51.             // calculate
  52.             ans += solve(level + 1) ;
  53.             // revert back --> UNDO
  54.             queen[level] = -1 ;
  55.         }
  56.     }
  57.  
  58.     return ans ;
  59. }
  60.  
  61. int main()
  62. {
  63.     cin >> n;
  64.     queen = vector<int>(n,-1) ;
  65.     cout << solve(0) << endl ;
  66. }
Tags: cp queen Nqeen
Advertisement
Add Comment
Please, Sign In to add comment