30. N-Queen Problem
The problem can be found at the following link: Question Link
Note: Sorry for uploading late, my exam is going on.
Problem Description
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens can attack each other. Given an integer n, find all distinct solutions to the n-queens puzzle. Each solution contains distinct board configurations of the n-queens placement, where the solutions are a permutation of [1, 2, 3,..., n] in increasing order. Here, the number in the i-th place denotes that the i-th column queen is placed in the row with that number.
Examples:
Input:
n = 1Output:
[1]Explanation: Only one queen can be placed in the single cell available.
Input:
n = 4Output:
[[2, 4, 1, 3], [3, 1, 4, 2]]Explanation: These are the 2 possible solutions.
My Approach
Backtracking Setup:
We use a recursive backtracking approach to explore all possible positions for the queens on the board. The function
btis responsible for placing queens on the board, column by column.An array
row[]keeps track of the row positions of the queens in each column.
Checking for Validity:
The
placefunction checks whether placing a queen at a specific row and column is valid. It ensures that no two queens can attack each other by checking for row and diagonal conflicts.
Recursive Backtracking:
The backtracking function tries to place a queen in each row of the current column and then recursively attempts to place queens in subsequent columns. If a valid configuration is found, it is stored in the result.
Final Output:
The result is a list of all valid configurations where no two queens can attack each other.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n!), as the problem involves generating all permutations of queen placements, and each placement requires checking validity, which takes linear time.
Expected Auxiliary Space Complexity: O(n²), due to the recursion stack and the space used to store the solutions.
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