52_N-Queens II
Last updated
Last updated
Input: 4
Output: 2
Explanation:
There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
def helper(row):
if row == n:
# global output
self.output += 1
return
for col in range(n):
if all(abs(col-b) not in (0, row-a)
for a, b in enumerate(col_index[ :row])):
col_index[row] = col
helper(row + 1)
self.output = 0
col_index = [0] * n
helper(0)
return self.output