n queens problem using backtracking program in java

import java.io.*;
class operation
{
int x[]=new int[20];
int count=0;
public boolean place(int row,int column)
{
int i;
for(i=1;i<=row-1;i++)
{ //checking for column and diagonal conflicts
if(x[i] == column)
return false;
else
if(Math.abs(x[i] – column) == Math.abs(i – row))
return false;
}
return true;
}
public void Queen(int row,int n)
{
int column;
for(column=1;column<=n;column++)
{
if(place(row,column))
{
x[row] = column;
if(row==n)
print_board(n);//printing the board configuration
else //try next queen with next position
Queen(row+1,n);
}
}
}

public void print_board(int n)
{
int i;
System.out.println(“\n\nSolution :”+(++count));
for(i=1;i<=n;i++)
{
System.out.print(” “+i);
}
for(i=1;i<=n;i++)
{
System.out.print(“\n\n”+i);
for(int j=1;j<=n;j++)// for nXn board
{
if(x[i]==j)
System.out.print(” Q”);
else
System.out.print(” -“);
}
}
}
}
class BacktrackDemo
{
public static void main (String args[] )throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println(“Enter no Of Queens”);
int n=Integer.parseInt(in.readLine());
operation op=new operation();
op.Queen(1,n);
}
}

OUTPUT:

Enter no 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 – –

NIRAJ AHER

Founder of Java Engineering Programs. Follow me on Google+ ,Linked in.

You may also like...

2 Responses

  1. Akash Agte says:

    program chukicha kashala deto!!

Leave a Reply

Your email address will not be published. Required fields are marked *