-
Notifications
You must be signed in to change notification settings - Fork 0
/
a_106_Nqueen_oneSolution.java
78 lines (66 loc) · 2.01 KB
/
a_106_Nqueen_oneSolution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class a_106_Nqueen_oneSolution {
public static boolean isSafe(char chess[][], int row, int col){
// verticals up
for(int i = row-1 ; i>=0 ; i--){
if(chess[i][col] == 'Q'){
return false ;
}
}
// left diagonal
for(int i=row-1, j=col-1 ; i>=0 && j>=0; i--, j--){
if(chess[i][j] == 'Q'){
return false;
}
}
// right diagonal
for(int i=row-1, j=col+1 ; i>=0 && j<chess.length; i--, j++){
if(chess[i][j] == 'Q'){
return false;
}
}
return true ;
}
public static boolean nQueen(char chess[][], int row){
// base case
if(row == chess.length) {
return true;
}
// colums loop
for(int j=0; j<chess.length; j++){
if(isSafe(chess,row,j) ){
chess[row][j] = 'Q' ;
if( nQueen(chess, row+1) ) {
return true ;
}
chess[row][j] = 'x' ; // backtracking step
}
}
return false ;
}
public static void printchess(char chess[][]){
System.out.println("------chess board------");
for(int i=0; i<chess.length; i++){
for(int j=0; j<chess.length ; j++){
System.out.print(chess[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int n = 9 ;
char chess[][] = new char[n][n] ;
// initialize
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
chess[i][j] = 'x' ;
}
}
if( nQueen(chess, 0) ){
System.out.println("Solution are possible");
printchess(chess);
}
else{
System.out.println("Solution are Not possible");
}
}
}