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