Advertisement
spider68

nQueen problem

Mar 23rd, 2020 (edited)
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4. int a[10][10];
  5. void print(int n)
  6. {
  7.     cout<<"[";
  8.     for(int i=0;i<n;i++)
  9.     for(int j=0;j<n;j++)
  10.     if(a[j][i]==1)cout<<j+1<<" ";
  11.     cout<<"] ";
  12. }
  13. bool safe(int row,int col,int n)
  14. {
  15.     int i=row,j=col;
  16.     while(i>=0&&j>=0)
  17.     {
  18.         if(a[i][j]==1)return false;
  19.         i--; j--;
  20.     }
  21.     i=row,j=col;
  22.     while(i<n&&j>=0)
  23.     {
  24.         if(a[i][j]==1)return false;
  25.         i++; j--;
  26.     }
  27.     j=col;
  28.     while(j>=0)
  29.     {
  30.         if(a[row][j]==1)return false;
  31.         j--;
  32.     }
  33.     return true;
  34. }
  35. bool queen(int col,int n)
  36. {
  37.     if(col==n)
  38.     {
  39.         print(n);
  40.         return true;
  41.     }
  42.     bool res=false;
  43.     for(int i=0;i<n;i++)
  44.     {
  45.         if(safe(i,col,n))
  46.         {
  47.             a[i][col]=1;
  48.             res=queen(col+1,n)||res;
  49.             a[i][col]=0;
  50.         }
  51.     }
  52.     return res;
  53. }
  54. int main()
  55. {
  56.     int i,j,m,n,t;
  57.     cin>>t;
  58.     while(t--)
  59.     {
  60.         cin>>n;
  61.         memset(a,0,sizeof(a));
  62.         if(queen(0,n)==false)cout<<-1;
  63.         cout<<endl;
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement