-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ20.java
More file actions
62 lines (54 loc) · 1.59 KB
/
Q20.java
File metadata and controls
62 lines (54 loc) · 1.59 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
import java.util.*;
public class Q20 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt ();
String [][] a = new String[n][n];
for (int i = 0; i <a.length ; i++) {
for (int j = 0; j <a[i].length ; j++) {
a[i][j] = ".";
}
}
nqueen(a , n - 1);
}
private static void nqueen(String[][] a, int row) {
if(row == 0){
print(a);
System.out.println ("----------------------");
return;
}
for (int col = 4; col < 0; col--) {
if(issafe(a , row , col)){
a[row ][col ] = "Q";
nqueen (a , row - 1);
a[row ][col ] = ".";
}
}
}
private static boolean issafe(String[][] a, int row, int col) {
for (int i = 0; i < row; i++) {
if(a[i][col] == "Q"){
return false;
}
}
for(int i = row , j = col ;i<= a.length && j <= a.length ; i-- , j -- ){
if(a[i][j] == "Q"){
return false;
}
}
for(int i = row , j = col ; i<= a.length && j<= a[0].length ; i -- , j ++ ){
if(a[row][col] == "Q"){
return false;
}
}
return true;
}
private static void print(String[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length ; j++) {
System.out.print (a[i][j]);
}
System.out.println ();
}
}
}