N-Queens — LeetCode 51 Python Solution
- Problem
- #51
- 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 all distinct solutions to the n-queens puzzle.
Example
- 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
Python solution
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def dfs(i: int):
if i == n:
ans.append(["".join(row) for row in g])
return
for j in range(n):
if col[j] + dg[i + j] + udg[n - i + j] == 0:
g[i][j] = "Q"
col[j] = dg[i + j] = udg[n - i + j] = 1
dfs(i + 1)
col[j] = dg[i + j] = udg[n - i + j] = 0
g[i][j] = "."
ans = []
g = [["."] * n for _ in range(n)]
col = [0] * n
dg = [0] * (n << 1)
udg = [0] * (n << 1)
dfs(0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times n!) |
| Space | O(n) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 51. N-Queens 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 NeetCode 150.
Frequently asked questions
- How hard is LeetCode 51. N-Queens?
- LeetCode 51. N-Queens is rated Hard on LeetCode.
- What is the time complexity of LeetCode 51. N-Queens?
- The Python solution on this page runs in O(n^2 \times n!).
- What is the space complexity of LeetCode 51. N-Queens?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 51. N-Queens cover?
- LeetCode 51. N-Queens is tagged Array and Backtracking on LeetCode.