0% found this document useful (0 votes)
23 views2 pages

ADA PGM 12

The document outlines a C/C++ program to solve the N Queen's problem using backtracking. It includes an algorithm that checks for valid placements of queens on an n x n chessboard and a program that implements this algorithm. The program prompts the user for the number of queens and outputs all possible solutions or indicates if no solution is found.

Uploaded by

vikasl.24.beai
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)
23 views2 pages

ADA PGM 12

The document outlines a C/C++ program to solve the N Queen's problem using backtracking. It includes an algorithm that checks for valid placements of queens on an n x n chessboard and a program that implements this algorithm. The program prompts the user for the number of queens and outputs all possible solutions or indicates if no solution is found.

Uploaded by

vikasl.24.beai
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/ 2

12. Design and implement C/C++ Program for N Queen's problem using Backtracking.

Algorithm:
/* outputs all possible acceptable positions of n queens on n x n chessboard */
// Initialize x [ ] to zero
// Set k = 1 start with first queen
Repeat for i = 1 to n // try all columns one by one for kth queen
if Place (k, i) true then
{
x(k) = i // place kth queen in column i
if (k=n)
all queens placed and hence print output (x[ ])
else
NQueens(K+1,n) //try for next queen
}
Place (k,i)
/* finds if kth queen in kth row can be placed in column i or not; returns true if queen can be
placed */
// x[1,2, . . . k-1] have been defined
//queens at (p, q) & (r, s) attack if |p-r| = |q-s|
Repeat for j = 1 to (k-1)
if any earlier jth queen is in ith column ( x[j]= i)
or in same diagonal ( abs(x[ j] - i) = abs( j - k) )
then kth queen cannot be placed (return false)
return true (as all positions checked and no objection)

Program:

#include <stdio.h>
int count=0,x[5];
int main()
{
int n;
printf("\n enter the number of queen");
scanf("%d",&n);
nqueen(1,n);
if(count==0)
printf("\n no solution found");
else
printf("\n number of solution found is:%d",count);
return 0;
}
int place(int k,int i)
{
int j; for(j=1;j<k;j++)
if((x[j]==i)||(abs(x[j]-i)==abs(j-k)))
return 0;
return 1;
}
nqueen(int k,int n)
{
int i,j,p; for(i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
{
count++;
printf("solution=%d",count); printf("\n"); for(j=1;j<=n;j++)
{
for(p=1;p<=n;p++)
if(x[j]==p)
printf("$\t");
else
printf("0\t");
printf("\n");
}
printf("\n");
}
else
nqueen(k+1,n);
}
}
return 0;
}

You might also like