Cod sursa(job #1657490)

Utilizator SolcanMihaiSolcan Mihai Andrei SolcanMihai Data 20 martie 2016 15:24:18
Problema Problema Damelor Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <cstdio>

using namespace std;

int n;
int mat[15][15];
int nr = 0;
int nrDame = 0;

int v1[4] = {-1, 1, 1, -1};
int v2[4] = {1, 1, -1, -1};

int linie[15];
int coloana[15];

void citire()
{
    scanf("%d", &n);
}

bool isValid(int k, int l)
{
    for(int i = 0; i < nrDame; i++)
    {
        if(linie[i] == k)
        {
            return false;
        }

        if(coloana[i] == l)
        {
            return false;
        }

        int tmp1 = k - linie[i];
        int tmp2 = l - coloana[i];

        if(tmp1 < 0)
        {
            tmp1 = -tmp1;
        }

        if(tmp2 < 0)
        {
            tmp2 = -tmp2;
        }

        if(tmp1 == tmp2)
        {
            return false;
        }
    }

    return true;
}

void afisare()
{
    for(int i = 0; i < n; i++)
    {
        printf("%d ", coloana[i] + 1);
    }

    printf("\n");
}

void backtrack(int k, int l)
{
    if(k == n)
    {
        if(nrDame != n)
        {
            return;
        }

        if(nr == 0)
        {
            afisare();
        }

        nr++;
    }
    else
    {
        if(isValid(k, l))
        {
            linie[nrDame] = k;
            coloana[nrDame] = l;

            nrDame++;

            int tmp1, tmp2;

            tmp1 = k;
            tmp2 = l + 1;

            if(tmp2 == n)
            {
                tmp1++;
                tmp2 = 0;
            }

            backtrack(k + 1, 0);

            nrDame--;

            backtrack(tmp1, tmp2);
        }
        else
        {
            int tmp1, tmp2;

            tmp1 = k;
            tmp2 = l + 1;

            if(tmp2 == n)
            {
                tmp1++;
                tmp2 = 0;
            }

            backtrack(tmp1, tmp2);
        }
    }
}

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

    citire();
    backtrack(0, 0);

    printf("%d", nr);

    return 0;
}