Skip to content

Commit 1a0d77a

Browse files
committed
added python solution for 0052-n-queens-ii
1 parent f989fdc commit 1a0d77a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

python/0052-n-queens-ii.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def totalNQueens(self, n: int) -> int:
3+
answer = 0
4+
5+
cols = set()
6+
posdiag = set()
7+
negdiag = set()
8+
9+
def backtrack(i):
10+
if i == n:
11+
nonlocal answer
12+
answer += 1
13+
return
14+
15+
for j in range(n):
16+
if j in cols or (i+j) in posdiag or (i-j) in negdiag:
17+
continue
18+
19+
cols.add(j)
20+
posdiag.add(i+j)
21+
negdiag.add(i-j)
22+
23+
backtrack(i+1)
24+
25+
cols.remove(j)
26+
posdiag.remove(i+j)
27+
negdiag.remove(i-j)
28+
29+
backtrack(0)
30+
return answer

0 commit comments

Comments
 (0)