Cod sursa(job #2289649)

Utilizator ZappaManIosif Adrian-Mihai ZappaMan Data 24 noiembrie 2018 23:05:32
Problema Problema Damelor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <stdio.h>
#include <vector>

using  namespace std;

const int NMAX = 15;
int N;

vector<bool> col(NMAX, false);
vector<bool> diag(2*NMAX+1, false);
vector<bool> antidiag(2*NMAX+1, false);
vector<bool>  row(NMAX, false);
vector<int> sol(NMAX, -1);

bool showed = false;
int total = 0;

void backtrack(int ix) {
   if (ix == N) {
      if (!showed) {
         for (int i = 1; i <= N; ++i) {
            printf("%d ", sol[i]);
         }
         showed = true;
         printf("\n");
      }
      total += 1;
      return;
   }

   for (int i = 1; i <= N; ++i) {
      int col_ix = i;
      int nix = ix + 1;
      if (col[col_ix] || diag[col_ix + nix] ||
            antidiag[N + col_ix - nix]) {
         continue;
      }

      sol[nix] = col_ix;

      col[col_ix] = true;
      diag[col_ix + nix] = true;
      antidiag[N + col_ix - nix] = true;

      backtrack(nix);

      col[col_ix] = false;
      diag[col_ix + nix] = false;
      antidiag[N + col_ix - nix] = false;

   }

}

int main() {
   freopen("damesah.in", "r", stdin);
   freopen("damesah.out", "w", stdout);

   scanf("%d", &N);

   backtrack(0);

   printf("%d", total);

   fclose(stdin);
   fclose(stdout);
   return 0;
}