tungggg

NQueensProblem_Backtrack

Feb 9th, 2022 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. int n;
  4. int x[100]; bool d1[100]={true}, d2[100]={true}; bool cot[100]={true};
  5. int chess [100][100];
  6. int res=0;
  7. void show(){
  8.     for(int i=1;i<100;i++){
  9.         for(int j=1;j<100;j++){
  10.             chess[i][j]=0;
  11.         }
  12.     }
  13.     for(int i=1;i<=n;i++){
  14.         chess[i][x[i]]=1;
  15.     }
  16.     for(int i=1;i<=n;i++){
  17.         for(int j=1;j<=n;j++){
  18.             cout<<chess[i][j]<<" ";
  19.         }
  20.         cout<<endl;
  21.     }
  22. }
  23. void backtrack (int i){
  24.     // duyet het tat ca kha nang co the co cua x[i];
  25.     if(i==n+1){
  26.         show();
  27.         cout<<endl;
  28.         res++;
  29.         return ;
  30.     }
  31.     else {
  32.         for(int j=1;j<=n;j++){
  33.             // quan hau toa do (i,j) se quan li cot=j , d1=i-j+n; d2=i+j-1;
  34.             if (cot[j]==1 && d1[i-j+n]==1 && d2[i+j-1]==1){
  35.                 x[i]=j;
  36.                 cot[j]=d1[i-j+n]=d2[i+j-1]=0;
  37.                 backtrack(i+1);
  38.                 cot[j]=d1[i-j+n]=d2[i+j-1]=1;
  39.             }
  40.         }
  41.     }
  42. }
  43. int main(){
  44.     cin>>n;
  45.     for(int i=1;i<=100;i++){
  46.         cot[i]=d1[i]=d2[i]=1;
  47.     }
  48.     backtrack(1);
  49.     cout<<res<<endl;
  50.     return 0;
  51. }
Add Comment
Please, Sign In to add comment