-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path52.n-queens-ii.py
44 lines (36 loc) · 1.03 KB
/
52.n-queens-ii.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#
# @lc app=leetcode id=52 lang=python3
#
# [52] N-Queens II
#
# @lc code=start
# TAGS: Backtracking
class Solution:
# 72 ms, 43.92%. Time: O(N!). Space: O(N^2)
def totalNQueens(self, n: int) -> int:
def not_available(step, i, used):
if i in used:
return True
for j in range(1, step + 1):
if (step - j, i - j) in used:
return True
if (step - j, i + j) in used:
return True
return False
def dfs(step=0, used=set()):
if step == n:
return 1
rv = 0
for i in range(n):
if not_available(step, i, used):
continue
# add to used list
used.add((step, i))
used.add(i)
rv += dfs(step + 1)
# remove from used list
used.discard(i)
used.discard((step, i))
return rv
return dfs()
# @lc code=end