forked from vishnu2k60/HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathN-Queens.java
88 lines (75 loc) · 2.53 KB
/
N-Queens.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
79
80
81
82
83
84
85
86
87
88
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> ans = new ArrayList<>();
combinations(new boolean[n][n], 0,n,ans,0,0);
return ans;
}
public boolean isQueenSafe(boolean[][] board, int row, int col) {
for(int i=0;i<board.length;i++) {
if(board[i][col] == true) {
return false;
}
}
for(int i=0;i<board[0].length;i++) {
if(board[row][i] == true) {
return false;
}
}
for(int i=row+1,j=col+1; i<board.length&&j<board[0].length;i++,j++) {
if(board[i][j] == true) {
return false;
}
}
for(int i=row-1,j=col-1; i>=0&&j>=0;i--,j--) {
if(board[i][j] == true) {
return false;
}
}
for(int i=row+1,j=col-1; i<board.length&&j>=0;i++,j--) {
if(board[i][j] == true) {
return false;
}
}
for(int i=row-1,j=col+1; i>=0&&j<board[0].length;i--,j++) {
if(board[i][j] == true) {
return false;
}
}
return true;
}
public void combinations(boolean[][] board, int qpsf, int qtbp, List<List<String>> ans, int row, int col) {
if(qpsf == qtbp) {
List<String> temp = new ArrayList<>();
for(int i=0;i<board.length;i++) {
String str = "";
for(int j=0;j<board[0].length;j++) {
if(board[i][j] == true) {
str+="Q";
}
else {
str+=".";
}
}
temp.add(str);
}
ans.add(new ArrayList<>(temp));
return;
}
for(int i=col;i<board[0].length;i++) {
if(board[row][i] == false && isQueenSafe(board,row,i)) {
board[row][i] = true;
combinations(board,qpsf+1,qtbp,ans,row,i);
board[row][i] = false;
}
}
for(int i=row+1;i<board.length;i++) {
for(int j=0;j<board[0].length;j++) {
if(board[i][j] == false && isQueenSafe(board,i,j)){
board[i][j] = true;
combinations(board,qpsf+1,qtbp,ans,i,j);
board[i][j] = false;
}
}
}
}
}