Hard
N-Queens
Hard
0 submissions
50 coins
+200 XP
Array
Backtracking
Problem Description
## Problem
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.
Given an integer `n`, return the **number of distinct solutions** to the n-queens puzzle.
Two queens attack each other if they are in the same row, column, or diagonal.
## Examples
**Example 1:**
```
Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle.
```
**Example 2:**
```
Input: n = 1
Output: 1
```
**Example 3:**
```
Input: n = 5
Output: 10
```
## Approach Hints
Use backtracking. Place queens row by row. For each row, try every column and check if the placement is safe (no conflict in column, main diagonal, or anti-diagonal). Use sets to track occupied columns and diagonals for O(1) conflict checks.
Constraints
- `1 <= n <= 9`
Need help?
Connect with expert programmers for real-time collaborative coding, video meetings, and whiteboard sessions via CodeConnect.
Video Call
Whiteboard
Live Coding
Screen Share