N-Queens LeetCode solution in Python

1
class Solution:
2
def solveNQueens(self, n: int) -> List[List[str]]:
3
coord = self.findNextRows(0, n)
4
ans = []
5
for c in coord:
6
temp = []
7
for j in c:
8
temp.append("." * j + "Q" + "." * (n - j - 1))
9
ans.append(temp)
10
return ans
11

12
def findNextRows(self, i, n, h_occ=set(), d_occ=set(), ad_occ=set()):
13
"""
14
h_occ: occupied horizontal coordinate
15
d_occ: occupied diagonal
16
ad_occ: occupied anti-diagonal
17
"""
18
ans = []
19
if i == n:
20
return [[]]
21
for j in range(n):
22
if (
23
(j not in h_occ)
24
and (j - i not in d_occ)
25
and ((j - n + 1) + i not in ad_occ)
26
):
27
h_occ.add(j)
28
d_occ.add(j - i)
29
ad_occ.add((j - n + 1) + i)
30
temp = self.findNextRows(i + 1, n, h_occ, d_occ, ad_occ)
31
h_occ.remove(j)
32
d_occ.remove(j - i)
33
ad_occ.remove((j - n + 1) + i)
34
ans += [[j] + l for l in temp]
35
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0