-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathn_queen.java
More file actions
69 lines (61 loc) · 1.4 KB
/
Copy pathn_queen.java
File metadata and controls
69 lines (61 loc) · 1.4 KB
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
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
import java.lang.*;
class GFG {
public static boolean isSafeToPut(int p , int[][] sol , int q , int n){
int i = p , j = q ;
for (int k = 0 ;k < n ; k++ ){
if(sol[i][k] == 1 || sol[k][j] == 1){
return false ;
}
}
while(i >= 0 && j >= 0){
if(sol[i][j] == 1){
return false ;
}
i--;
j--;
}
i = p ;
j = q ;
while(i>=0 && j < n){
if(sol[i][j] == 1){
return false;
}
i--;
j++;
}
return true ;
}
public static boolean nqueen(int n , int[][] sol , int i)
{
if(i == n){
for(int l = 0 ; l< n ; l++){
for(int k = 0 ; k < n ; k++){
System.out.print(sol[l][k]+ " ");
}
System.out.print("\n");
}
System.out.print("\n");
return false ;
}
for(int j = 0 ; j < n ; j++){
if( isSafeToPut( i , sol , j , n) == true){
sol[i][j] = 1 ;
boolean kyasabsahi = nqueen(n , sol , i+1);
if(kyasabsahi == true){
return true ;
}
sol[i][j] = 0 ;
}
}
return false ;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sol[][] = new int[n][n];
nqueen( n , sol , 0 );
}
}