πDay 3. N-Queen Problem π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
The N-Queen problem is a classic combinatorial problem where you are tasked with placing N queens on an N x N chessboard such that no two queens threaten each other. This means:
No two queens share the same row.
No two queens share the same column.
No two queens share the same diagonal.
Your task is to return a list of all possible solutions, where each solution represents the board configuration as a list of integers. Each integer in the list represents the column index (1-based) of the queen for each row.
π Example Walkthrough:
Example 1
Input:
N = 4
Output:
[[2, 4, 1, 3], [3, 1, 4, 2]]
Explanation:
For N = 4, two solutions exist:
Solution 1:
Solution 2:
Example 2
Input:
N = 1
Output:
[[1]]
Explanation:
For N = 1, only one solution exists:
Solution 1:
Constraints
1 <= N <= 10
π― My Approach:
The N-Queen problem can be efficiently solved using bitwise operations to track occupied columns and diagonals:
Use three bitmasks:
cols: Tracks occupied columns.d1: Tracks occupied left diagonals (sum of row and column indices is constant).d2: Tracks occupied right diagonals (difference of row and column indices is constant).
Backtrack recursively:
Place a queen in a valid column of the current row.
Mark the column and diagonals as occupied.
Move to the next row.
If a solution is found, add it to the result.
Backtrack by unmarking the column and diagonals.
This method reduces unnecessary checks and speeds up the solution.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N!), where N is the number of queens. Each row has N possibilities initially, and this reduces with each row.
Worst-Case Time Complexity: O(N!)
For the first queen, there are
Nchoices.For the second queen, there are
N-1choices, and so on.Thus, the total complexity is
O(N * (N-1) * (N-2) * ... * 1) = O(N!).
Expected Auxiliary Space Complexity: O(N), where N is the space used for recursive calls and the row configuration array.
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated