Cod sursa(job #3149441)

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

using namespace std;

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

int st[20], n, fr[20], cnt;
int sol[] = {0, 0, 0, 0, 2, 10, 4, 40, 92};

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

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);
    return 0;
}