/*
* queen.C -
* Print all the solutions to the 8-queens problem.
*/
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
void printBoard(int nums[], int size);
int isInvalidPlacement(int nums[], int curr_row, int new_pos);
int queen(int nums[], int curr_row, int n)
{
int new_pos, count;
assert(0 <= curr_row && curr_row <= n);
if (curr_row == n) {
printBoard(nums, n);
return 1;
}
count = 0;
for (new_pos = 1; new_pos <= n; new_pos++) {
if (isInvalidPlacement(nums, curr_row, new_pos))
continue;
nums[curr_row] = new_pos;
count += queen( nums, curr_row + 1, n );
}
return count;
}
int isInvalidPlacement(int nums[], int curr_row, int new_pos)
{
int ind;
for (ind = 0; ind < curr_row; ind++) {
if (nums[ind] == new_pos)
return 1;
if (abs(nums[ind] - new_pos) == (curr_row - ind))
return 1;
}
return 0;
}
void printBoard(int nums[], int size)
{
int ind, jnd;
for (ind = 0; ind < size; ind++) {
for (jnd = 1; jnd <= size; jnd++)
printf("%c", (jnd == nums[ind]) ? '1' : '0');
printf("\n");
}
printf("\n");
}
int main()
{
int num, count, nums[40];
num = 8;
count = queen(nums, 0, num);
printf("Computed all the valid placements of queens on"
" boards of size %dx%d.\n"
"There are %d such solutions.\n", num, num, count);
return 0;
}
|