Post

Leetcode 52. N-Queens II

Explanation for Leetcode 52 - N-Queens II, and its solution in Python.

Problem

Leetcode 52 - N-Queens II

Example:

1
2
3
4
5
Input: n = 4
Output: 2

Input: n = 1
Output: 1

Approach

Similar to the question Leetcode-51, we can solve this using a counter instead of array to save all the board state

Here is the Python code for the solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
    def totalNQueens(self, n: int) -> int:
        col = set()
        posDiag = set()
        negDiag = set()

        res = 0
        def dfs(r):
            nonlocal res
            if r == n:
                res += 1
                return
            
            for c in range(n):
                if c in col or (r+c) in posDiag or (r-c) in negDiag:
                    continue
                
                col.add(c)
                posDiag.add(r+c)
                negDiag.add(r-c)

                dfs(r+1)

                col.remove(c)
                posDiag.remove(r+c)
                negDiag.remove(r-c)
    
        dfs(0)
        return res

Time Complexity and Space Complexity

Time Complexity: $O(n!)$

Space Complexity: $O(n)$

This post is licensed under CC BY 4.0 by the author.