-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path052. N-Queens II.py
40 lines (33 loc) · 1.04 KB
/
052. 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
# Follow up for N-Queens problem.
# Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution(object):
result = 0
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
cols = []
self.search(n, cols)
return self.result
def search(self, n, cols):
if len(cols) == n:
self.result += 1
return
for col in range(n):
if not self.isValid(cols, col):
continue
self.search(n, cols + [col])
def isValid(self, cols, col):
currentRowNumber = len(cols)
for i in range(currentRowNumber):
# same column
if cols[i] == col:
return False
# left-top to right-bottom
if i - cols[i] == currentRowNumber - col:
return False
# right-top to left-bottom
if i + cols[i] == currentRowNumber + col:
return False
return True