When implementing an algorithm for all possible solution of an n-Queen problem, i found that the same solution is reached by many branches. Is there any good way to generate every unique solutions to the n-Queens problem? How to avoid the duplicate solutions generated by the different branches (except store and compare)?
Here is what i have tried, for the first solution: http://www.ideone.com/hDpr3
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* crude */
#define QUEEN 'Q'
#define BLANK '.'
int is_valid (char **board, int n, int a, int b)
{
int i, j;
for (i=0; i<n; i++)
{
if (board[a][i] == QUEEN)
return 0;
if (board[i][b] == QUEEN)
return 0;
}
for (i=a, j=b; (i>=0) && (j>=0); i--, j--)
{
if (board[i][j] == QUEEN)
return 0;
}
for (i=a, j=b; (i<n) && (j<n); i++, j++)
{
if (board[i][j] == QUEEN)
return 0;
}
for (i=a, j=b; (i>=0) && (j<n); i--, j++)
{
if (board[i][j] == QUEEN)
return 0;
}
for (i=a, j=b; (i<n) && (j>=0); i++, j--)
{
if (board[i][j] == QUEEN)
return 0;
}
return 1;
}
void show_board (char **board, int n)
{
int i, j;
for (i=0; i<n; i++)
{
printf ("\n");
for (j=0; j<n; j++)
{
printf (" %c", board[i][j]);
}
}
}
int nqdfs_all (char **board, int n, int d)
{
int i, j, ret = 0;
/* the last queen was placed on the last depth
* therefore this dfs branch in the recursion
* tree is a solution, return 1
*/
if (d == n)
{
/* Print whenever we find one solution */
printf ("\n");
show_board (board, n);
return 1;
}
/* check all position */
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
if (is_valid (board, n, i, j))
{
board[i][j] = QUEEN;
nqdfs_all (board, n, d + 1);
board[i][j] = BLANK;
}
}
}
return ret;
}
int nqdfs_first (char **board, int n, int d)
{
int i, j, ret = 0;
/* the last queen was placed on the last depth
* therefore this dfs branch in the recursion
* tree is a solution, return 1
*/
if (d == n)
return 1;
/* check all position */
for (i=0; i<n; i++)
{
for (j=0; j<n; j++)
{
if (is_valid (board, n, i, j))
{
board[i][j] = QUEEN;
ret = nqdfs_first (board, n, d + 1);
if (ret)
{
/* if the first branch is found, tell about its
* success to its parent, we will not look in other
* solutions in this function.
*/
return ret;
}
else
{
/* this was not a successful path, so replace the
* queen with a blank, and prepare board for next
* pass
*/
board[i][j] = BLANK;
}
}
}
}
return ret;
}
int main (void)
{
char **board;
int n, i, j, ret;
printf ("\nEnter \"n\": ");
scanf ("%d", &n);
board = malloc (sizeof (char *) * n);
for (i=0; i<n; i++)
{
board[i] = malloc (sizeof (char) * n);
memset (board[i], BLANK, n * sizeof (char));
}
nqdfs_first (board, n, 0);
show_board (board, n);
printf ("\n");
return 0;
}
To generate all possible solution i have used the same code nqdfs_all ()
function, but did not return the control to the parent, instead continued enumerating and checking. A call to this function displays the duplicate results reached by different branches.