Cod sursa(job #3149440)

Utilizator David2007David Preda David2007 Data 8 septembrie 2023 16:46:47
Problema Problema Damelor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("damesah.in");
ofstream fout("damesah.out");

int st[20], n, fr[20], cnt;

void Afisare(){
    cnt++;
    if(cnt == 1)
    {
        for(int i = 1; i <= n; i++){
            fout << st[i] << " ";
        }
        fout << "\n";
    }
}

bool Valid(int top, int i){
    int j;
    ///verificam daca avem dama pe coloana i
    if(fr[i] == 1) return false;
    for(j = 1; j < top; j++)
        /// abs = modul
        /// daca diferenta dintre linii este egala cu diferenta dintre coloane
        /// atunci dama i este pe o diagonala cu dama j
        if(abs(j - top) == abs(st[j] - i)) return false;
    return true;
}

void Back(int top){
    int i;
    if(top == n + 1)
        Afisare();
    else{
        for(i = 1; i <= n; i++){
            if(Valid(top, i)){
                fr[i] = 1;
                st[top] = i;
                Back(top + 1);
                fr[i] = 0;
            }
        }
    }
}

int main()
{
    fin >> n;
    Back(1);
    fout << cnt;
    return 0;
}