Skip to content

Commit 8f26377

Browse files
Merge pull request neetcode-gh#3225 from dp3why/main
Modified Solution: 0051-n-queens.java
2 parents 488a7da + 18cac3d commit 8f26377

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

java/0051-n-queens.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Solution 1:
12
class Solution {
23

34
public List<List<String>> solveNQueens(int n) {
@@ -55,3 +56,71 @@ public boolean isSafe(boolean[][] board, int row, int col) {
5556
return true;
5657
}
5758
}
59+
60+
61+
62+
// Solution 2:
63+
/*
64+
* This solution uses 3 hashsets to check whether the current queen has conflicts with previous
65+
* columns and two diagonals, avoiding the use of 2D boolean array and the isSafe checking function.
66+
*
67+
*/
68+
class Solution {
69+
public List<List<String>> solveNQueens(int n) {
70+
List<List<String>> result = new ArrayList<>();
71+
List<String> cur = new ArrayList<>();
72+
if (n <= 0) {
73+
return result;
74+
}
75+
Set<Integer> leftSet = new HashSet<>(); // diag \ row - col
76+
Set<Integer> rightSet = new HashSet<>(); // diag / row + col
77+
Set<Integer> colSet = new HashSet<>(); // column | col
78+
dfs(n, result, cur, leftSet, rightSet, colSet);
79+
return result;
80+
}
81+
82+
private void dfs(int n, List<List<String>> result, List<String> cur, Set<Integer> leftSet,
83+
Set<Integer> rightSet, Set<Integer> colSet) {
84+
if (cur.size() == n) {
85+
result.add(new ArrayList(cur));
86+
return;
87+
}
88+
int row = cur.size();
89+
// i is column index
90+
for (int i = 0; i < n; i++) {
91+
if (leftSet.contains(row - i) || rightSet.contains(row + i) || colSet.contains(i)) {
92+
continue;
93+
}
94+
// current col index is added to the solution list cur
95+
cur.add(convert(n, i));
96+
leftSet.add(row - i);
97+
rightSet.add(row + i);
98+
colSet.add(i);
99+
// go to dfs next level
100+
dfs(n, result, cur, leftSet, rightSet, colSet);
101+
// backtracking
102+
cur.remove(cur.size() - 1);
103+
leftSet.remove(row - i);
104+
rightSet.remove(row + i);
105+
colSet.remove(i);
106+
107+
}
108+
}
109+
110+
private String convert(int n, int col) {
111+
StringBuilder res = new StringBuilder();
112+
for (int i = 0; i < n; i++) {
113+
if (i == col) {
114+
res.append("Q");
115+
} else {
116+
res.append(".");
117+
}
118+
}
119+
return res.toString();
120+
}
121+
}
122+
123+
124+
125+
126+

0 commit comments

Comments
 (0)