Problem Description
Place n queens on an n x n chessboard such that no two queens attack each other. Return all distinct board configurations where each configuration is represented as a list of strings. Each string represents a row of the chessboard, using "Q" for queens and "." for empty spaces.
Key Insights
- Use backtracking to explore potential positions row by row.
- Use sets to track which columns and diagonals are under attack.
- Diagonals can be tracked by (row - col) and (row + col), ensuring that queens do not conflict along any diagonal.
- Recursively build each valid board configuration and backtrack when a conflict arises.
Space and Time Complexity
Time Complexity: O(n!) in the worst-case scenario, as the solution explores permutations for queen placements. Space Complexity: O(n^2) for storing board configurations and O(n) for recursion stack and conflict-tracking sets.
Solution
We use a backtracking algorithm that places queens row by row. For each row, we try placing a queen in each column. Before placing, we check if the column, main diagonal (row - col), and anti-diagonal (row + col) are free using dedicated sets. If a queen can be safely placed, we mark the column and diagonals as occupied and recurse to the next row. Once all rows are processed, the board configuration is a valid solution and is added to the result. After that, we backtrack by unmarking the sets and removing the queen from the board. This systematic approach ensures all possible configurations are considered.