NQueen Problem
N-Queen Problem
[Java Implementation]
Program:-
* @(#)8QueenProblem.java
*
*
* @author Suyash Bhalla
* @version 1.00 2015/11/12
*/
class NQueenProblem{
static int x[];
static int cnt=0;
static int N;
public static void main(String args[]){
N=8;
x=new int[N+1];
solve(1,8);
System.out.println("Total Solutions:"+cnt);
}
public static 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;
}
public static void solve(int k,int n){
for(int i=1;i<=n;i++){
if(place(k,i)){
x[k]=i;
if(k==n){
printBoard(x);
}else{
solve(k+1,n);
}
}
}
}
public static void printBoard(int x[]){
cnt++;
for(int i=1;i<=8;i++){
for(int j=1;j<=8;j++){
if(j==x[i]){
System.out.print(j+" ");
}else{
System.out.print(0+" ");
}
}
System.out.println();
}
System.out.println();
}
}
Output:-
1 0 0 0 0 0 0 0
0 0 0 0 5 0 0 0
0 0 0 0 0 0 0 8
0 0 0 0 0 6 0 0
0 0 3 0 0 0 0 0
0 0 0 0 0 0 7 0
0 2 0 0 0 0 0 0
0 0 0 4 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 6 0 0
0 0 0 0 0 0 0 8
0 0 3 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 4 0 0 0 0
0 2 0 0 0 0 0 0
0 0 0 0 5 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 4 0 0 0 0
0 0 0 0 0 6 0 0
0 0 0 0 0 0 0 8
0 2 0 0 0 0 0 0
0 0 0 0 5 0 0 0
0 0 3 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 0 5 0 0 0
0 0 0 0 0 0 0 8
0 2 0 0 0 0 0 0
0 0 0 4 0 0 0 0
0 0 0 0 0 6 0 0
0 0 3 0 0 0 0 0
0 2 0 0 0 0 0 0
0 0 0 4 0 0 0 0
0 0 0 0 0 6 0 0
0 0 0 0 0 0 0 8
0 0 3 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 0 5 0 0 0
.
.
.
.
.
.
0 0 0 0 0 0 0 8
0 0 0 4 0 0 0 0
1 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0
0 0 0 0 0 6 0 0
0 2 0 0 0 0 0 0
0 0 0 0 0 0 7 0
0 0 0 0 5 0 0 0
Total Solutions:92
Labels: 8 Queen Problem, N-Queen Problem, NQueen Problem Java Implementation