HardNo. 0051

N-Queens — LeetCode 51 Python Solution

Topics
Array, Backtracking
On a study list
NeetCode 150
Reading time
4 min

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

PythonSolution
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 ans

Complexity

Time
O(n2 × n!)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0052N-Queens IIHard
0047Permutations IIMedium
0046PermutationsMedium
0039Combination SumMedium
0040Combination Sum IIMedium
0078SubsetsMedium

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(n2 × 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.