|
42 | 42 | public final class NQueens { |
43 | 43 |
|
44 | 44 | // Store occupied rows for constant time safety check |
45 | | - private static final Set<Integer> OCCUPIED_ROWS = new HashSet<>(); |
| 45 | + private static final Set<Integer> OCROWS = new HashSet<>(); |
46 | 46 |
|
47 | 47 | // Store occupied main diagonals (row - column) |
48 | | - private static final Set<Integer> OCCUPIED_DIAGONALS = new HashSet<>(); |
| 48 | + private static final Set<Integer> OCDIAG = new HashSet<>(); |
49 | 49 |
|
50 | 50 | // Store occupied anti-diagonals (row + columns) |
51 | | - private static final Set<Integer> OCCUPIED_ANTI_DIAGONALS = new HashSet<>(); |
| 51 | + private static final Set<Integer> OCANTIDIAG = new HashSet<>(); |
52 | 52 |
|
53 | 53 | private NQueens() { |
54 | 54 | } |
@@ -101,24 +101,27 @@ private static void getSolution(int boardSize, List<List<String>> solutions, int |
101 | 101 | columns[columnIndex] = rowIndex; |
102 | 102 |
|
103 | 103 | // Skip current position if row or diagonal is already occupied |
104 | | - if (OCCUPIED_ROWS.contains(rowIndex) || OCCUPIED_DIAGONALS.contains(rowIndex - columnIndex) || |
105 | | - OCCUPIED_ANTI_DIAGONALS.contains(rowIndex + columnIndex)) { |
| 104 | + boolean isROp = OCROWS.contains(rowIndex); |
| 105 | + |
| 106 | + boolean isDOp = OCDIAG.contains(rowIndex - columnIndex) || OCANTIDIAG.contains(rowIndex + columnIndex); |
| 107 | + |
| 108 | + if (isROp || isDOp) { |
106 | 109 | continue; |
107 | 110 | } |
108 | 111 |
|
109 | 112 | // Mark current row and diagonal as occupied |
110 | | - OCCUPIED_ROWS.add(rowIndex); |
111 | | - OCCUPIED_DIAGONALS.add(rowIndex - columnIndex); |
112 | | - OCCUPIED_ANTI_DIAGONALS.add(rowIndex + columnIndex); |
| 113 | + OCROWS.add(rowIndex); |
| 114 | + OCDIAG.add(rowIndex - columnIndex); |
| 115 | + OCANTIDIAG.add(rowIndex + columnIndex); |
113 | 116 |
|
114 | 117 | // Move to the next column after placing current queen |
115 | 118 | getSolution(boardSize, solutions, columns, columnIndex + 1); |
116 | 119 |
|
117 | 120 | // Backtrack by removing current queen |
118 | 121 |
|
119 | | - OCCUPIED_ROWS.remove(rowIndex); |
120 | | - OCCUPIED_DIAGONALS.remove(rowIndex - columnIndex); |
121 | | - OCCUPIED_ANTI_DIAGONALS.remove(rowIndex + columnIndex); |
| 122 | + OCROWS.remove(rowIndex); |
| 123 | + OCDIAG.remove(rowIndex - columnIndex); |
| 124 | + OCANTIDIAG.remove(rowIndex + columnIndex); |
122 | 125 | } |
123 | 126 | } |
124 | 127 |
|
|
0 commit comments