Cod sursa(job #2169532)

Utilizator SaphyrosMarcus Sergiu David Saphyros Data 14 martie 2018 16:00:37
Problema Problema Damelor Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>

using namespace std;

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

int n, k = 0;
int tabla[15][15];
int regine[15];

void countSol();
void tipSol();
bool safe(int row, int col);
bool util(int col);
void rez();

int main()
{
    fin >> n;
    rez();

    return 0;
}

void countSol()
{
    k++;
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<n; j++)
            if (tabla[i][j])
                regine[i] = j+1;
    }
}

void tipSol()
{
    for (int i=0; i<n; i++)
        fout << regine[i] << " ";
    fout << "\n" << k;
}

bool safe(int row, int col)
{
    int i, j;

    // rand
    for (j=0; j<col; j++)
        if (tabla[row][j])
            return false;

    // diagonala principala
    for (i=row, j=col; i>=0 && j>=0; i--, j--)
        if (tabla[i][j])
            return false;

    // diagonala secundara
    for (i=row, j=col; i<n && j>=0; i++, j--)
        if (tabla[i][j])
            return false;

    return true;
}

bool util(int col)
{
    // toate plasate
    if (col == n)
    {
        countSol();
        return true;
    }

    // incearca coloana
    for (int i=0; i<n; i++)
    {
        if (safe(i, col))
        {
            tabla[i][col] = 1;
            util(col+1); // recursie

            tabla[i][col] = 0; // backtrack
        }
    }

    return false;
}

void rez()
{
    if (util(0))
    {
        fout << -1;
        return;
    }

    tipSol();

    return;
}