Pagini recente » Cod sursa (job #1048320) | Cod sursa (job #994761) | Cod sursa (job #1231552) | Cod sursa (job #972112) | Cod sursa (job #2437143)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#define maxQueens 100
typedef struct coords{
int X, Y;
}Coords;
int factorial = 1;
int N;
int number_of_solutions = 0;
int queens[maxQueens];
FILE *read, *write;
bool goodSolution(int step)
{
if (step == N - 1)
{
number_of_solutions ++;
return true;
}
return false;
}
bool goodQueen(int step)
{
for (int i = 0; i < step; i++)
{
if (queens[i] == queens[step] ||
(abs(i - step) == abs(queens[i] - queens[step])))
return false;
}
return true;
}
void print()
{
for (int i = 0; i < N; i++)
{
factorial *= (i + 1);
if (i != N - 1)
fprintf(write, "%d ", queens[i]);
else
fprintf(write, "%d\n", queens[i]);
}
}
void back(int step)
{
if (step > N)
return;
for (int i = 1; i <= N; i++)
{
queens[step] = i;
if (goodQueen(step) == true)
{
if (goodSolution(step) == true)
{
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;
}