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

Queens

The document presents a C program that solves the N-Queens problem, allowing the user to input the number of queens. It uses recursive backtracking to find all possible arrangements of queens on a chessboard such that no two queens threaten each other. The program displays each solution and counts the total number of solutions found.

Uploaded by

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

Queens

The document presents a C program that solves the N-Queens problem, allowing the user to input the number of queens. It uses recursive backtracking to find all possible arrangements of queens on a chessboard such that no two queens threaten each other. The program displays each solution and counts the total number of solutions found.

Uploaded by

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

N-Queen

#include <stdio.h>

int x[10], count;

int nQueens(int k, int n);

int place(int k, int i);

int display(int n);

int main()

int n;

printf("Enter the number of queens: ");

scanf("%d", &n);

nQueens(1, n);

if (count == 0)

printf("\n No possible solutions for the number of queens!");

else

printf("\nNumber of possible solutions for %d queens is: %d", n, count);

return 0;

int nQueens(int k, int n) {

int i;

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

if ( place(k, i) ) {

x[k] = i;

if (k == n)

display(n);

else

nQueens(k + 1, n);

}
N-Queen

int place(int k, int i) {

int j;

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

if ( (x[j] == i) || (j - x[j] == k - i) || (j + x[j] == k + i) )

return 0;

return 1;

}int display(int n) {

int i, j;

char c[10][10];

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

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

c[i][j] = '-';

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

c[i][x[i]] = 'Q';

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

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

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

printf("%c\t", c[i][j]);

printf("\n");

OUTPUT:

/tmp/xPIbINWlFL.o

Enter the number of queens: 4

Solution #1:

- Q - -

- - - Q
N-Queen

Q - - -

- - Q -

Solution #2:

- - Q -

Q - - -

- - - Q

- Q - -

Number of possible solutions for 4 queens is: 2

=== Code Execution Successful ===

You might also like