Home › Forums › C Programming › n queen problem

- This topic has 0 replies, 1 voice, and was last updated 12 years, 2 months ago by DelbertJardine.

- AuthorPosts
- May 27, 2009 at 6:11 am #2202DelbertJardineParticipant
Hello,

I have an N Queen code which produces proper output in matrix form and it will also gives all distinct result…I want the given code to be modified as follows:

1) it should take the input as coordinates

ex: enter the no of queens

4

enter the coordinates:

0 12)when it takes the input in coordinate, it should check for that coordinate in all the possible matrix

if the coordinate is found in any of the matrix then it should display message called queen placed and display that particular matrix

if it is not found then it should given an output as illegal move…Please can anyone help me with this problem….

thank you…code:

#include

#include

#include

#include//using namespace std;

int const MAX=20;

#define TRUE 1

#define FALSE 0void print_solution(int n,int x[])

{char c[10][10];

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

{

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

{

c*[j]=’x’;*

}

}*//place the queens on the board*

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

{

c*[x**]=’Q’;*

}*//print where the queens have been placed on chess board*

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

{

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

{

cout<*[j];*

}

cout<<"n";

}*}**//function to check whether the queen can be placed successfully or not*

int place(int x[],int k)

{

for(int i=1; i{

//check whether the queens attach vertically or diagonally

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

{

return FALSE;//queen can not be placed in the kth column

}

}

//kth queen can be successfully placed

return TRUE;

}

void nqueens(int n)

{

int x[10];

int count=0; //number of solutions

int k=1; //select the first queen*x[k]=0;**while(k!=0) //A queen exists?*

{

x[k]+=1; //place the kth queen in next column

//satisfy both explicit and implicit constraint

while((x[k]<=n)&&(!place(x,k)))

{

x[k]+=1; //place queen in next column

}

//if queen successfully placed?

if(x[k]<=n)

{

//if all queens are placed

if(k==n)

{

count++;

cout<<"nsolutin"<print_solution(n,x); *}*

else

{

k++; //select the next queen

x[k]=0; //but do not place

}

}

else

{

//backtrack and select previous queen

k–;

}

}

//no more solution exist

return;

}*void main()*

{

int n;

clrscr();

cout<<"Enter the no. of queensn";

cin>>n;

nqueens(n);

getch();

}*Example of an output:*

enter the no of queens

4

solution 1 is*xQxx*

xxxQ

Qxxx

xxQx*solution 2 is**xxQx*

Qxxx

xxxQ

xQxx

*Author**Posts*

*Viewing 0 reply threads*

- The forum ‘C Programming’ is closed to new topics and replies.