ValerianBenchea

BACKTRACKING Problema damelor

Oct 7th, 2021
789
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. int x[101], n;
  5.  
  6. int e_bun(int k)
  7. {
  8.     for(int i=1; i<=k-1; i++)
  9.         if(x[i]==x[k] || abs(i-k)==abs(x[i]-x[k]))
  10.             return 0;
  11.     return 1;
  12. }
  13.  
  14. void afis(int k)
  15. {
  16.     int i, j;
  17.     for(i=1; i<=k; i++)
  18.     {
  19.         for(j=1; j<=k; j++)
  20.             if(j==x[i])
  21.                 cout<<'D'<<' ';
  22.             else
  23.                 cout<<'#'<<' ';
  24.         cout<<'\n';
  25.     }
  26. }
  27.  
  28. void back()
  29. {
  30.     int k=1;
  31.     x[k]=0;
  32.     while(k>0)
  33.     {
  34.         if(x[k]<n)
  35.         {
  36.             x[k]++;
  37.             if(e_bun(k))
  38.                 if(k==n)
  39.                 {
  40.                     afis(k);
  41.                     cout<<'\n';
  42.                 }
  43.                 else
  44.                 {
  45.                     k++;
  46.                     x[k]=0;
  47.                 }
  48.         }
  49.         else
  50.             k--;
  51.     }
  52. }
  53.  
  54. int main()
  55. {
  56.     cin>>n;
  57.     back();
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment