Cod sursa(job #2207205)

Utilizator AndreiVisoiuAndrei Visoiu AndreiVisoiu Data 25 mai 2018 10:05:15
Problema Problema Damelor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("damesah.in");
ofstream out("damesah.out");

const int maxN = 14;
int sol, x[maxN], n;
bool col[maxN], mainDiag[maxN*2], secDiag[maxN*2];
void mark(int l, int c, bool v = true) {
    col[c] = v;
    mainDiag[n+c-l] = v;
    secDiag[c+l-1] = v;
}
bool valid(int l, int c) {
    if(!col[c] && !mainDiag[n+c-l] && !secDiag[c+l-1])
        return true;
    return false;
}
void backt(int k) {
    if(k <= n) {
        for(int i = 1; i <= n; i++) {
            x[k] = i;
            if(valid(k, i)) {
                mark(k, i);
                backt(k+1);
                mark(k, i, false);
            }
        }
    } else {
        sol++;
        if(sol == 1) {
            for(int i = 1; i < k; i++)
                out << x[i] << ' ';
            out << '\n';
        }
    }
}
int main()
{
    in >> n;
    backt(1);
    out << sol;
    return 0;
}