//Program to implement n Queen
import java.io.*;
class Nqueen
{
int n;
int x[];
void read()throws IOException
{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader cin=new BufferedReader(in);
System.out.println("enter number of queens");
n=Integer.parseInt(cin.readLine());
x=new int [n+1];
}
boolean place(int k,int i)
{
for(int j=1;j<=k-1;j++)
{
if(x[j]= =i || Math.abs(x[j]-i)= =Math.abs(k-j))
return false;
}
return true;
}
void nqueen(int k)
{
for(int i=1;i<=n;i++)
{
if (place(k,i))
{
x[k]=i;
if (k==n)
{
for(int j=1;j<=n;j++)
System.out.print(x[j]+" ");
System.out.println();
}
else
nqueen(k+1);
}
}
}
}
class Nqueentest
{
public static void main (String args[])throws IOException
{
Nqueen nq=new Nqueen();
nq.read();
nq.nqueen(1);
}
}
/*OUTPUT:
Enter number of queens
4
2 4 1 3
3 1 4 2
Process Exit...*/
0 comments:
Post a Comment