The N-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other (no two share the same row, column, or diagonal). Given an integer n, return all distinct solutions to the N-queens puzzle. Each solution contains a distinct board configuration where 'Q' indicates a queen and '.' indicates an empty space.
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There are two distinct solutions to the 4-queens puzzle.
Output: [["Q"]]
We place queens one row at a time. For each row we try every column position and check whether it is safe (no conflict in column, main diagonal, or anti-diagonal). We use three boolean sets to track occupied columns and diagonals for O(1) conflict checks.
- Maintain sets for occupied columns, main diagonals (row-col), and anti-diagonals (row+col).
- Recursively try each column in the current row; skip if any set contains the position.
- Place the queen (update sets and board array), recurse to the next row, then backtrack.
- When all n rows are filled, convert the board array to a list of strings and add to results.
Complexity Analysis:
Time complexity: O(n!) in the worst case (n choices for row 1, n-2 for row 2, etc.).
Space complexity: O(n^2) for the board plus O(n) for the recursion stack and sets.