N-Queens Program:
import java.util.Scanner;class Queens
{
static int n;
static int temp[],ar[];
//static int count=0;
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter size of Matrix");
n=sc.nextInt();
ar=new int[n+1];
temp=new int[n+1];
queens(0);
//System.out.println(count);
}
public static void queens(int k)
{
for(int i=1;i<=n;i++)
{
if(place(k,i))
{
ar[k]=i;
if(k==n)
{
for(int j=1;j<=n;j++)
{
//System.out.print(ar[j] + " ");
temp[j]=ar[j];
}
//System.out.println();
print_fun(temp);
//count++;
}
else
{
queens(k+1);
}
}
}
}
public static boolean place(int k,int i)
{
for(int j=1;j<=k;j++)
{
if((i==ar[j]) || (j-k)*(j-k)==(i-ar[j])*(i-ar[j]))
{
return false;
}
}
return true;
}
public static void print_fun(int temp[])
{
for(int x=1;x<=n;x++)
{
for(int y=1;y<=n;y++)
{
if(temp[x]==y)
{
System.out.print(" Q ");
}
else
{
System.out.print(" . ");
}
}
System.out.println();
}
System.out.println();
}
}
Enter size of Matrix
4
. . Q .
Q . . .
. . . Q
. Q . .
0 Comments
Please don't enter any spam link in comment box.
Emoji