0% found this document useful (0 votes)
4 views3 pages

N Queens

The document presents a C program that solves the N queens problem using backtracking. It prompts the user for the number of queens and outputs all possible solutions for placing the queens on a chessboard without threatening each other. The program includes functions for printing solutions and checking valid placements of queens.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

N Queens

The document presents a C program that solves the N queens problem using backtracking. It prompts the user for the number of queens and outputs all possible solutions for placing the queens on a chessboard without threatening each other. The program includes functions for printing solutions and checking valid placements of queens.

Uploaded by

golladeepu19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

N queens:

#include <stdio.h>

#include <stdlib.h>

int board[20], count;

int main()

int n,i,j;
void queen(int row, int n);

printf("-N queens problem using backtracking-");

printf("\n\nenter number of queens:");

scanf("%d", &n);
queen(1,n);

return 0;

void print(int n)

int i,j;

printf("\n\nsolution %d:\n\n", ++count);


for(i=1; i<=n; i++)

printf("\t%d", i);

for(i=1; i<=n; i++){

printf("\n\n%d", i);

for(j=1; j<=n; j++)


{

if(board[i]==j)

printf("\tQ");

else

printf("\t-");

}
}

int place(int row, int column)

int i;

for(i=1; i<=row-1; i++){

if(board[i]==column)
return 0;

else

if(abs(board[i]-column)==abs(i-row))

return 0;
}

return 1;

void queen(int row, int n)

int column;

for(column=1; column<=n; column++)


{

if(place(row,column))

board[row]=column;

if(row==n)
print(n);

else

queen(row+1, n);

}
Output:
-N queens problem using backtracking-

enter number of queens:4

solution 1:

1 2 3 4

1 - Q - -

2 - - - Q

3 Q - - -

4 - - Q -

solution 2:

1 2 3 4

1 - - Q -

2 Q - - -

3 - - - Q

4 - Q - -

You might also like