> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# N-Queens Python Solution with Tests

> Tested Python solution for LeetCode 51 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 51, Hard. Topics: Array, Backtracking. [View on LeetCode](https://leetcode.com/problems/n-queens/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 51   # by problem number
lcpy gen -s n_queens   # by problem name
```

## 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 *all distinct solutions to the **n-queens puzzle***. You may return the answer in **any order**.

Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2020/11/13/queens.jpg)

```
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
```

```
Input: n = 1
Output: [["Q"]]
```

### Constraints

* 1 \<= n \<= 9

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/n_queens/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/n_queens/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n!)
    # Space: O(n) excluding output
    def solve_n_queens(self, n: int) -> list[list[str]]:
        result: list[list[str]] = []
        cols: set[int] = set()
        diag1: set[int] = set()  # r - c
        diag2: set[int] = set()  # r + c
        queens: list[int] = []  # column index per row

        def can_place(row: int, col: int) -> bool:
            return col not in cols and row - col not in diag1 and row + col not in diag2

        def backtrack(row: int) -> None:
            if row == n:
                board: list[str] = []
                for q_col in queens:
                    board.append("." * q_col + "Q" + "." * (n - q_col - 1))
                result.append(board)
                return
            for col in range(n):
                if not can_place(row, col):
                    continue
                cols.add(col)
                diag1.add(row - col)
                diag2.add(row + col)
                queens.append(col)
                backtrack(row + 1)
                queens.pop()
                diag2.discard(row + col)
                diag1.discard(row - col)
                cols.discard(col)

        backtrack(0)
        return result
```

## Complexity

| Time  | Space                 |
| ----- | --------------------- |
| O(n!) | O(n) excluding output |

## Tags

[Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
