Place n queens on an n×n chessboard so that no two attack each other (same row, column, or diagonal). Return all valid arrangements, where each solution shows the column position of the queen in each row.
Examples:
Input: n = 4 Output: [[2, 4, 1, 3], [3, 1, 4, 2]] Explanation: We mainly print column numbers (from first to last row) of every possible configuration.
Use backtracking to place queens row by row, checking if each position is safe. If safe, place the queen and move to the next row; otherwise, backtrack and try another position. Store the solution when all queens are placed.
Time Complexity: O(n!) We try placing queens in different positions, and choices reduce at each step due to conflicts. Auxiliary Space: O(n^2) We use an n × n board and recursion stack for backtracking.
[Expected Approach 1] Backtracking with Hashing
This is mainly an optimization over the above approach, we optimize the isSafe() by using three arrays to track occupied columns and diagonals. A position is considered valid only if its column and both diagonals are free. When placing a queen, mark these arrays, and while backtracking, unmark them. This allows checking safe positions in constant time O(1).
Output
2 4 1 3
3 1 4 2
Time Complexity: O(n!) – we try placing a queen in every row recursively, pruning invalid positions using the arrays. Auxiliary Space: O(n)
[Expected Approach 2] Backtracking with Bit-masking - O(n!) Time and O(n) Space
This is a further optimization for small board sizes. The idea is to use three variables to track occupied rows and diagonals. At each step, use bit operations to quickly find safe positions. Place a queen, update the variables, and move forward; if no position works, backtrack and try other options until all solutions are found.