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