|
| 1 | +// Solution 1: |
1 | 2 | class Solution { |
2 | 3 |
|
3 | 4 | public List<List<String>> solveNQueens(int n) { |
@@ -55,3 +56,71 @@ public boolean isSafe(boolean[][] board, int row, int col) { |
55 | 56 | return true; |
56 | 57 | } |
57 | 58 | } |
| 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