A.K.A - "N-Queens Problem"
(Note: I computed till 15. N-Queens is only defined for N>= 4)
Manipulate the constant named "MAX"
Program:
#include<stdio.h>
#include<conio.h>
#define MAX 8
int q[MAX] = { 0 };
void printem()
{
int i, j,k;
for (i = 0; i < MAX; i++) {
printf("\n\t");
for (j = q[i], k = MAX - j; j > 0; j--) {
printf("-");
}
printf("X");
for (; k > 0; k--) {
printf("-");
}
}//Outer for ends
}
int dist(int x, int y)
{
if (x > y)
return (x - y);
return (y - x);
}
int match(int i, int j)
{
int k, xi, xj;
for (k = 0; k < i; k++) {
xi = k;
xj = q[k];
if (xi == i || xj == j)
return (0);
if (dist(i, xi) == dist(j, xj))
return (0);
}
for (; k < MAX; k++) {
q[k] = -1;
}
return (1);
}
int main()
{
int i = 0, k, ci, cj;
clrscr();
for (k = 0; k < MAX;) {
if (i >= MAX) // My Version of Back tracking
{
printf("nBackTracked... %dth Queen", k + 1);
k--;
while ((q[k] + 1) >= MAX)
k--;
i = q[k] + 1;
}
ci = i++;
if (match(k, ci) == 1) //k - x axis. ci - y axis.
{
i = 0;
q[k] = ci;
k++;
}
} // for loop ends
printf("nThe Queens: ");
for (i = 0; i < MAX; i++)
printf("n%d: %d", i + 1, q[i]);
//printem(); //remove comment to see how it looks on the board
getch();
}
Comments
Post a Comment