-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQunsProb.java
55 lines (40 loc) · 969 Bytes
/
NQunsProb.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
public class NQunsProb{
static int arr[][],n;
static boolean Safe(int row,int col){
int i,j;
for (i=col;i>=0;i--)
if(arr[row][i]==1)
return false;
for (i=col,j=row;i>=0 && j<n;j++,i--)
if(arr[j][i]==1)
return false;
for (i=col,j=row;i>=0 && j>=0;j--,i--)
if(arr[j][i]==1)
return false;
return true;
}
static boolean Solve(int col){
if(col>=n)
return true;
for(int t=0;t<n;t++){
if(Safe(t,col)){
arr[t][col]=1;
if(Solve(col+1))
return true;
}
arr[t][col]=0;
}
return false;
}
public static void main(String[] args){
n=4;
int i,j;
arr= new int [n][n];
if(Solve(0))
for(i=0;i<n;i++){
for(j=0;j<n;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
}
}
}