Advertisement
vlatkovski

N Queens problem

Jun 25th, 2018
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define endl '\n'
  3. typedef long long ll;
  4. using namespace std;
  5.  
  6.  
  7. const int N = 8;
  8. int total = 0;
  9.  
  10. void print(vector<int> &v) {
  11.   cout << "{\n";
  12.   for (int i = 0; i < N; ++i) {
  13.     cout << "  {";
  14.     for (int j = 0; j < N; ++j) {
  15.       cout << (v[i] == j) << ", ";
  16.     }
  17.     cout << "},\n";
  18.   }
  19.   cout << "},\n";
  20. }
  21.  
  22.  
  23. void f(vector<int> v, int row) {
  24.   if (row == N) {
  25.     total++;
  26.     print(v);
  27.     return;
  28.   }
  29.   for (int col = 0; col < N; ++col) {
  30.     bool ok = 1;
  31.     for (int i = 0; i < row; ++i) {
  32.       int j = v[i];
  33.       if (j == col || row+col == i+j || row-col == i-j) {
  34.         ok = 0;
  35.         break;
  36.       }
  37.     }
  38.     if (ok) {
  39.       v[row] = col;
  40.       f(v, row+1);
  41.     }
  42.   }
  43. }
  44.  
  45. void start() {
  46.   vector<int> v(N, -1);
  47.   for (int j = 0; j < N; ++j) {
  48.     v[0] = j;
  49.     f(v, 1);
  50.   }
  51. }
  52.  
  53. void main1() {
  54.  
  55.   start();
  56.   cout << "Total amount: " << total << endl;
  57.  
  58. }
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65. int main() {
  66.   std::ios::sync_with_stdio(false);
  67.   std::cin.tie(nullptr);
  68.   std::cout.tie(nullptr);
  69.   #ifdef _DEBUG
  70.   std::freopen("in.txt", "r", stdin);
  71.   std::freopen("out.txt", "w", stdout);
  72.   #endif
  73.   main1();
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement