Advertisement
STANAANDREY

pbdame

Jan 11th, 2020
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define NMAX 15
  5. int n;
  6. int st[NMAX];
  7. bool vis[NMAX];
  8. int sols;
  9.  
  10. inline bool valid(int top, int x)
  11. {
  12.     if (vis[x])
  13.         return false;
  14.  
  15.     for (int i = 1; i < top; i++)
  16.     {
  17.         if (abs(top - i) == abs(x - st[i]))//damaCurr(coord:top, x;) altele:linia i si col Ast[i]
  18.             return false;
  19.     }
  20.  
  21.     return true;
  22. }
  23.  
  24. inline void display()
  25. {
  26.     for (int i = 1; i <= n; i++)
  27.         cout << st[i] << ' ';
  28.     cout << '\n';
  29. }
  30.  
  31. void backtracking(int top)
  32. {
  33.     if (top == n + 1)
  34.     {
  35.         sols++;
  36.         if (sols == 1)
  37.             display();
  38.         return;
  39.     }
  40.  
  41.     for (int i = 1; i <= n; i++)
  42.     {
  43.         if (valid(top, i))
  44.         {
  45.             vis[i] = true;
  46.             st[top] = i;
  47.             backtracking(top + 1);
  48.             vis[i] = false;
  49.         }
  50.     }
  51. }
  52.  
  53. signed main()
  54. {
  55.     cin >> n;
  56.     backtracking(1);
  57.     cout << sols;
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement