| 10 | } |
| 11 | |
| 12 | private void dfs(int r, Set<Integer> diagonalsSet, Set<Integer> antiDiagonalsSet, Set<Integer> colsSet, int n) { |
| 13 | // Termination condition: If we have reached the end of the rows, |
| 14 | // we've placed all 'n' queens. |
| 15 | if (r == n) { |
| 16 | res++; |
| 17 | return; |
| 18 | } |
| 19 | for (int c = 0; c < n; c++) { |
| 20 | int currDiagonal = r - c; |
| 21 | int currAntiDiagonal = r + c; |
| 22 | // If there are queens on the current column, diagonal or |
| 23 | // anti-diagonal, skip this square. |
| 24 | if (colsSet.contains(c) || diagonalsSet.contains(currDiagonal) || antiDiagonalsSet.contains(currAntiDiagonal)) { |
| 25 | continue; |
| 26 | } |
| 27 | // Place the queen by marking the current column, diagonal, and |
| 28 | // anti−diagonal as occupied. |
| 29 | colsSet.add(c); |
| 30 | diagonalsSet.add(currDiagonal); |
| 31 | antiDiagonalsSet.add(currAntiDiagonal); |
| 32 | // Recursively move to the next row to continue placing queens. |
| 33 | dfs(r + 1, diagonalsSet, antiDiagonalsSet, colsSet, n); |
| 34 | // Backtrack by removing the current column, diagonal, and |
| 35 | // anti−diagonal from the hash sets. |
| 36 | colsSet.remove(c); |
| 37 | diagonalsSet.remove(currDiagonal); |
| 38 | antiDiagonalsSet.remove(currAntiDiagonal); |
| 39 | } |
| 40 | } |
| 41 | } |