Cod sursa(job #2302384)

Utilizator NicusorTelescu Nicolae Nicusor Data 14 decembrie 2018 15:44:20
Problema Problema Damelor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <cstdio>

using namespace std;

int nrSolutii, v[14];

void backtracking(int nivel, int n, FILE* out)
{
    if (nivel == n + 1)
    {
        nrSolutii++;
        if (nrSolutii == 1)
        {
            for (int i = 1 ; i <= n ; i++)
                fprintf(out,"%d ",v[i]);
            fprintf(out,"\n");
        }
    }
    else
    {
        // iau toate pozitiile pe care le poate lua dama de pe linia nivel
        for (int i = 1 ; i <= n ; i++)
        {
            int ok = 1;
            for (int k = 1 ; k <= nivel - 1 && ok ; k++)
            {
                if (nivel - k == i - v[k] || i == v[k] || nivel - k == v[k] - i)
                    ok = 0;
            }
            if (ok == 1)
            {
                v[nivel] = i;
                backtracking(nivel + 1,n,out);
                v[nivel] = 0;
            }
        }
    }
}

int main()
{
    FILE* in = fopen("damesah.in","r");
    FILE* out = fopen("damesah.out","w");

    int n(0);
    fscanf(in,"%d",&n);
    backtracking(1,n,out);
    fprintf(out,"%d",nrSolutii);
    return 0;
}