Pagini recente » Cod sursa (job #707325) | Cod sursa (job #1260035) | Cod sursa (job #1369675) | Cod sursa (job #1782159) | Cod sursa (job #2437261)
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
FILE *read, *write;
int N;
int number_of_solutions = 0;
int queens[5000];
bool goodQueen(int step)
{
for (int i = 0; i < step; i++)
{
if (queens[i] == queens[step] ||
(step - i == abs(queens[i] - queens[step])))
return false;
}
return true;
}
void print()
{
for (int i = 0; i < N; i++)
{
if (i != N - 1)
fprintf(write, "%d ", queens[i]);
else
fprintf(write, "%d\n", queens[i]);
}
}
void back(int step)
{
for (int i = 1; i <= N; i++)
{
queens[step] = i;
if (goodQueen(step) == true)
{
if (step == N - 1)
{
number_of_solutions ++;
if (number_of_solutions == 1)
print();
}
else
back(step + 1);
}
}
}
int main()
{
read = (FILE *) fopen("damesah.in", "r");
write = (FILE *) fopen("damesah.out", "w");
fscanf(read, "%d", &N);
back(0);
fprintf(write, "%d\n", number_of_solutions);
fclose(read);
fclose(write);
return 0;
}