Cod sursa(job #2683944)

Utilizator DVDPRODavid D DVDPRO Data 12 decembrie 2020 11:35:12
Problema Problema Damelor Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

int board[20][20], n, solutions;
bool firstsol=true;
vector<int> sol;

void read()
{
    fin>>n;
}

void showfirstsol()
{
    int chonkness=sol.size();
    for(int i=0; i<chonkness; i++)
        fout<<sol[i]+1<<" ";
    fout<<'\n';
}

bool isclear(int x, int a)
{
    if(board[x][a]==1)
        return 0;
    int chonkness=sol.size();
    for(int i=0; i<chonkness; i++)
        if(a==sol[i])
            return 0;
    //cout<<a<<" este o pozitie vailda\n";
    return 1;
}

void editboard(int x, int y, int value)
{
    int aux=x, auy=y;
    board[x][y]=value;
    while(aux<n && auy<n)
    {
        board[aux][auy]=value;
        aux++;
        auy++;
    }
    aux=x, auy=y;
    while(aux<n && auy>=0)
    {
        board[aux][auy]=value;
        aux++;
        auy--;
    }
    aux=x, auy=y;
    while(aux>=0 && auy<n)
    {
        board[aux][auy]=value;
        aux--;
        auy++;
    }
    aux=x, auy=y;
    while(aux>=0 && auy>=0)
    {
        board[aux][auy]=value;
        aux++;
        auy--;
    }
}

void backtrack(int k)
{
    if(k==n)
    {
        //cout<<"found one\n";
        solutions++;
        if(firstsol)
        {
            firstsol=0;
            showfirstsol();
        }
    }

    for(int i=0; i<n; i++)
        {

            if(isclear(k,i))
            {
                //cout<<"a\n";
                editboard(k,i,1);
                sol.push_back(i);
                backtrack(k+1);
                editboard(k,i,0);
                sol.pop_back();
            }
        }
}

int main()
{
    read();
    backtrack(0);
    fout<<solutions<<'\n';
    return 0;
}