Algorithm Day63 - N-Queens
🧩 Problem Description
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.
Return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the queen placements, represented as an array of strings, where 'Q'
and '.'
indicate a queen and an empty space, respectively.
💬 Example
Example 1
1 | Input: n = 4 |
Example 2
1 | Input: n = 1 |
💡 Intuition
This is a classic backtracking problem.
We need to try placing queens row by row, ensuring each placement is valid:
- A queen cannot share the same column.
- A queen cannot share the same diagonal.
We backtrack:
- Place a queen in a valid column for the current row.
- Move to the next row.
- If all rows are filled, store the board as one solution.
🔢 Java Code (Backtracking)
1 | import java.util.*; |
⏱ Complexity Analysis
Let n
be the board size:
- Time: O(n!) — Each row has up to
n
choices, pruning reduces but worst case exponential. - Space: O(n^2) for board + O(n) recursion depth.
✍️ Summary
- Use backtracking to try placing queens row by row.
- Check columns and diagonals for validity.
- Collect solutions when all rows are filled.
Related problems
lc-52
— N-Queens II (count solutions)