Cod sursa(job #1657350)

Utilizator SolcanMihaiSolcan Mihai Andrei SolcanMihai Data 20 martie 2016 13:41:33
Problema Problema Damelor Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 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};

bool linie[15];
bool coloana[15];

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

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

    printf("\n");
}

bool isValid(int k, int l)
{
    if(linie[k] == true)
    {
        return false;
    }

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

    int tmp1, tmp2;

    for(int j = 0; j < 4; j++)
    {
        tmp1 = k;
        tmp2 = l;

        for(int m = 0; m < n; m++)
        {
            tmp1 += v1[j];
            tmp2 += v2[j];

            if(tmp1 >= 0 && tmp1 < n && tmp2 >= 0 && tmp2 < n)
            {
                if(mat[tmp1][tmp2] == 1)
                {
                    return false;
                }
            }
            else
            {
                break;
            }
        }
    }

    return true;

    return true;
}

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

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

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

            int tmp1, tmp2;

            tmp1 = k;
            tmp2 = l + 1;

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

            linie[k] = true;
            coloana[l] = true;
            backtrack(tmp1, tmp2);
            linie[k] = false;
            coloana[l] = false;

            mat[k][l] = 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;
}