Cod sursa(job #3152549)

Utilizator petru-robuRobu Petru petru-robu Data 25 septembrie 2023 18:47:03
Problema Problema Damelor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("damesah.in");
ofstream fout("damesah.out");
int n, a[101][101]={0};
bool found = false;

void afis()
{
	for(int i=1; i<=n; i++)
	{
		for(int j=1; j<=n; j++)
			if(a[i][j])
            {
                fout<<j<<' ';
                break;
            }
	}
}

bool valid(int i, int j)
{
    for(int k=1; k<=n; k++)	
		if((a[i][k] && k!=j) || (a[k][j] && k!=i))
			return false;
    
    for(int row=i-1, col=j-1; row>=1 && col>=1; row--, col--)
        if(a[row][col])
            return false;
    
    for(int row=i-1, col=j+1; row>=1 && col<=n; row--, col++)
        if(a[row][col])
            return false;
    return true;
}

void back(int pas)
{
	if(pas == n+1)
    {
        afis();
        found = true;
    }
		
	
	for(int j=1; j<=n && !found; j++)
	{
		a[pas][j] = 1;
		if(valid(pas, j))
			back(pas+1);
        a[pas][j] = 0;
	}	
}


void solve()
{
    fin>>n;
    back(1);
}


int main()
{
    solve();
    return 0;
}