Pagini recente » Cod sursa (job #2753880) | Cod sursa (job #2091743) | Cod sursa (job #1298900) | Cod sursa (job #412327) | Cod sursa (job #2302384)
#include <cstdio>
using namespace std;
int nrSolutii, v[14];
void backtracking(int nivel, int n, FILE* out)
{
if (nivel == n + 1)
{
nrSolutii++;
if (nrSolutii == 1)
{
for (int i = 1 ; i <= n ; i++)
fprintf(out,"%d ",v[i]);
fprintf(out,"\n");
}
}
else
{
// iau toate pozitiile pe care le poate lua dama de pe linia nivel
for (int i = 1 ; i <= n ; i++)
{
int ok = 1;
for (int k = 1 ; k <= nivel - 1 && ok ; k++)
{
if (nivel - k == i - v[k] || i == v[k] || nivel - k == v[k] - i)
ok = 0;
}
if (ok == 1)
{
v[nivel] = i;
backtracking(nivel + 1,n,out);
v[nivel] = 0;
}
}
}
}
int main()
{
FILE* in = fopen("damesah.in","r");
FILE* out = fopen("damesah.out","w");
int n(0);
fscanf(in,"%d",&n);
backtracking(1,n,out);
fprintf(out,"%d",nrSolutii);
return 0;
}