Advertisement
edutedu

problema celor n dame puriterativ

Nov 19th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. int n, x[2000], nrsol=0;
  6.  
  7. void init(int k)
  8. {
  9.     x[k]=0;
  10. }
  11. int existaSuccesor(int k)
  12. {
  13.     return x[k]<n;
  14. }
  15. int solutie(int k)
  16. {
  17.     return k==n;
  18. }
  19. void tipar()
  20. {
  21.     /*for(int k=1; k<=n; k++)
  22.         cout<<"Dama "<<k<<" pe coloana "<<x[k]<<endl;
  23.         nrsol++;
  24.         cout<<endl<<endl;*/
  25.     for(int i=1; i<=n; i++)
  26.     {
  27.         for(int j=1; j<=n; j++)
  28.             if(x[i]==j)
  29.                cout<<" D ";
  30.             else
  31.                 cout<<" * ";
  32.         cout<<endl;
  33.     }
  34.     nrsol++;
  35.     cout<<endl;
  36. }
  37. int cont(int k)
  38. {
  39.     for(int i=1; i<k; i++)
  40.         if(x[k]==x[i]||k-i==abs(x[k]-x[i]))
  41.            return 0;
  42.     return 1;
  43. }
  44. void backt(int k)
  45. {
  46.     init(k);
  47.     while(existaSuccesor(k))
  48.     {
  49.         x[k]=x[k]+1;
  50.         if(cont(k))
  51.            if(solutie(k))
  52.               tipar();
  53.            else
  54.             backt(k+1);
  55.     }
  56. }
  57.  
  58. int main()
  59. {
  60.     cin>>n;
  61.     int k=1;
  62.     init(1);
  63.     while(k>0)
  64.         if(existaSuccesor(k))
  65.           {
  66.             x[k]=x[k]+1;
  67.             if(cont(k))
  68.                 if(solutie(k))
  69.                    tipar();
  70.             else
  71.             {
  72.                 k++;
  73.                 init(k);
  74.             }
  75.           }
  76.         else
  77.             k=k-1;
  78.     cout<<"Nr de solutii sunt: "<<nrsol<<endl;
  79.     //backt(k);
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement