Advertisement
xerpi

Problem P17921_ca: Reines (2)

Dec 19th, 2014
489
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6.  
  7. void escriure_tauler(const vector<int> &sp, int n)
  8. {
  9.     vector<vector<char> > m(n, vector<char>(n, '.'));
  10.    
  11.     for (int i = 0; i < n; i++) {
  12.         m[sp[i]][i] = 'Q';
  13.         for (int j = 0; j < n; j++) {
  14.             cout << m[j][i];
  15.         }
  16.         cout << endl;
  17.     }
  18.     cout << endl;
  19. }
  20.  
  21. bool legal(const vector<int> &sp, int q, int n, int y,
  22.     const vector<bool> &fila,
  23.     const vector<bool> &diag_pos,
  24.     const vector<bool> &diag_neg)
  25. {
  26.     return not (fila[y] or diag_pos[q+y] or diag_neg[(n-y)+q-1]);
  27. }
  28.  
  29. void reines(vector<int> &sp, int q, int n,
  30.     vector<bool> &fila,
  31.     vector<bool> &diag_pos,
  32.     vector<bool> &diag_neg)
  33. {
  34.     if (q == n) escriure_tauler(sp, n);
  35.     else {
  36.         for (int y = 0; y < n; y++) {
  37.             if (legal(sp, q, n, y, fila, diag_pos, diag_neg)) {
  38.                 sp[q] = y;
  39.                 fila[y] = true;
  40.                 diag_pos[q+y] = true;
  41.                 diag_neg[(n-y)+q-1] = true;
  42.                 reines(sp, q+1, n, fila, diag_pos, diag_neg);
  43.                 diag_neg[(n-y)+q-1] = false;
  44.                 diag_pos[q+y] = false;
  45.                 fila[y] = false;
  46.                 sp[q] = -1;
  47.             }
  48.         }
  49.     }
  50. }
  51.  
  52. int main()
  53. {
  54.     int n;
  55.     cin >> n;
  56.     vector<bool> fila(n, false),
  57.         diag_neg(2*n-1, false),
  58.         diag_pos(2*n-1, false);
  59.     vector<int> sp(n, -1);
  60.     reines(sp, 0, n, fila, diag_pos, diag_neg);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement