注意點:<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCta70OjSqrzGyv0NCjxwPsD919OjujwvcD4NCjxwPsrkyOs6IG4gPSA4PC9wPg0KPHA+yuSz9jogOTI8L3A+DQo8aDIgaWQ9"解題思路">解題思路
思路與 N-Queens 一樣,不過把原先用來最後拼裝的參數之類都去掉了,換了一個計數器來記錄數量。
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
self.col = [False] * n
self.diag = [False] * (2 * n)
self.anti_diag = [False] * (2 * n)
self.result = 0
self.recursive(0, n)
return self.result
def recursive(self, row, n):
if row == n:
self.result += 1
else:
for i in range(n):
if not self.col[i] and not self.diag[row + i] and not self.anti_diag[n - i + row]:
self.col[i] = self.diag[row + i] = self.anti_diag[n - i + row] = True
self.recursive(row + 1, n)
self.col[i] = self.diag[row + i] = self.anti_diag[n - i + row] = False
if __name__ == "__main__":
assert Solution().totalNQueens(8) == 92