-1

To practice what I've learned about backtracking algorithms, I'm trying to solve the N-Queen problem.

I've written some functions to check if a move is legal, but I can't see how to implement those using backtracking.

bool manger_ligne (int a[][4],int i) {
    for (int j=0;j<4;j++) {
        if (a[i][j] == 1)
            return false ;
    }

    return true;
}

bool manger_col (int a[][4],int j) {
    for (int i=0;i<4;i++) {
        if (a[i][j] == 1)
            return false ;
    }
    return true ; 
}

bool isTrue (int a[][4],int i,int j,int k) {
    if (k==0) {
        return 1;
    }
    if (i > 3 && j > 3) {
        return 0;
    }

    if (manger_diagonal(a, i, j) == true && manger_col(a, j) == true &&
        manger_ligne(a, i) == true) {
        a[i][j] = 1;
        if (isTrue(a, i, j+1 ,k) == true) {
            if (isTrue(a, i+1,j ,k) == true) //backtracking problem
                return true;
        }
        a[i][j] = 0;
    }
    return false ;
}
Bob__
  • 12,361
  • 3
  • 28
  • 42

1 Answers1

1

a few days ago I had to accomplish this task as a school task. This is a solution with 8 Queens. I solved it as follows:

In the main I call the function solveQn. Then the program does everything on it's own.

Bool solveNQ:

bool solveNQ(){
int board[N][N] = { 
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0}
};
if ( solveNQUtil(board, 0) == false )
{
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}

Bool solveNQUntil:

bool solveNQUtil(int board[N][N], int col){
if (col >= N)
    return true;
for (int i = 0; i < N; i++)
{
    if ( isSafe(board, i, col) )
    {
        board[i][col] = 1;
        if ( solveNQUtil(board, col + 1) )
            return true;
        board[i][col] = 0;
    }
}
return false;
}

Bool isSafe:

bool isSafe(int board[N][N], int row, int col){
int i, j;

for (i = 0; i < col; i++)
    if (board[row][i])
        return false;

for (i=row, j=col; i>=0 && j>=0; i--, j--)
    if (board[i][j])
        return false;

for (i=row, j=col; j>=0 && i<N; i++, j--)
    if (board[i][j])
        return false;

return true;
}

Output the solution:

void printSolution(int board[N][N]){
for (int i = 0; i < N; i++)
{
    for (int j = 0; j < N; j++)
        printf(" %d ", board[i][j]);
    printf("\n");
}
}

At the beginning of the code you need to define a global variable N with the value 8, in this case. You need to include the header stdbool.h as well, because here you would use Booleans.

V1le
  • 11
  • 3