N-Queens II — LeetCode 52 Python Solution
- Problem
- #52
- Pattern
- Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
- Input
- n = 4
- Output
- 2
- Explanation
- There are two distinct solutions to the 4-queens puzzle as shown.
Python solution
class Solution:
def totalNQueens(self, n: int) -> int:
def dfs(i: int):
if i == n:
nonlocal ans
ans += 1
return
for j in range(n):
a, b = i + j, i - j + n
if cols[j] or dg[a] or udg[b]:
continue
cols[j] = dg[a] = udg[b] = True
dfs(i + 1)
cols[j] = dg[a] = udg[b] = False
cols = [False] * 10
dg = [False] * 20
udg = [False] * 20
ans = 0
dfs(0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n!) |
| Space | O(n) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 52. N-Queens II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
On a study list
This problem is on Top Interview 150.
Frequently asked questions
- How hard is LeetCode 52. N-Queens II?
- LeetCode 52. N-Queens II is rated Hard on LeetCode.
- What is the time complexity of LeetCode 52. N-Queens II?
- The Python solution on this page runs in O(n!).
- What is the space complexity of LeetCode 52. N-Queens II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 52. N-Queens II cover?
- LeetCode 52. N-Queens II is tagged Backtracking on LeetCode.