Cod sursa(job #2279100)

Utilizator AndreiSorin26012001Cirpici Andrei Sorin AndreiSorin26012001 Data 8 noiembrie 2018 22:07:29
Problema Problema Damelor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <bits/stdc++.h>
#define DIM 15
using namespace std;

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

int n, sol[DIM], cont;
bool afisat;
bool coloana[DIM], diagonala_p[2*DIM], diagonala_s[2*DIM];

void golire( int x, int y )
{
    sol[x] = 0;
    coloana[y] = false;
    diagonala_s[x + y] = false;

    if( x <= y )
        diagonala_p[y - x + n] = false;
    else
        diagonala_p[x - y] = false;
}

bool OK( int x, int y )
{
    if( coloana[y] == true )
        return false;

    if( diagonala_s[x + y] == true )
        return false;

    if( x <= y )
    {
        if( diagonala_p[y - x + n] == true )
            return false;
    }
    else
    {
        if( diagonala_p[x - y] == true )
            return false;
    }

    return true;
}

bool plasare( int x, int y )
{
    if( !OK(x, y) )
        return false;

    sol[x] = y;
    coloana[y] = true;
    diagonala_s[x + y] = true;

    if( x <= y )
        diagonala_p[y - x + n] = true;
    else
        diagonala_p[x - y] = true;

    return true;
}

void afisare()
{
    if(afisat)
       return;

    afisat = true;
    for( int i = 1; i <= n; i++ )
        out<<sol[i]<<" ";
    out<<"\n";
}

void backt( int pas )
{
    if( pas == n + 1 )
    {
        afisare();
        cont++;
        return;
    }

    for( int i = 1; i <= n; i++ )
        if( plasare(pas, i) )
        {
            backt(pas + 1);
            golire(pas, i);
        }
}

int main()
{
    in>>n;

    backt(1);

    out<<cont;
    return 0;
}