Problem Description
Place n queens on an n x n chessboard such that no two queens can attack each other (i.e. no two queens share the same row, column, or diagonal). Return the number of distinct solutions.
Key Insights
- Uses backtracking to generate all possible placements on the board.
- Maintains sets (or equivalent data structures) to track columns and diagonals that are already threatened.
- Recursively places one queen per row, ensuring constraints are met before moving to the next row.
- When the last row is successfully reached, a valid arrangement is found and counted.
Space and Time Complexity
Time Complexity: O(n!) in the worst case due to the nature of recursive backtracking. Space Complexity: O(n) for the recursion stack and helper data structures for columns and diagonals.
Solution
We use a recursive backtracking approach where each recursion level corresponds to placing a queen on a specific row. Three sets (or similar structures) are used to check if a particular column or diagonal is already occupied by another queen:
- One set for tracking columns.
- One set for the "hill" diagonals (row - col remains constant).
- One set for the "dale" diagonals (row + col remains constant).
At each recursive call, we try placing a queen in each column of the current row. If the placement does not conflict with any previously placed queen, we mark the column and appropriate diagonals as occupied and move on to the next row. When a valid configuration for all rows is found, we increment our solution count. Finally, we backtrack by removing the last placed queen before trying the next possibility.