1. [52]N-Queens II
# The n-queens puzzle is the problem of placing n queens on an n x n chessboard
# such that no two queens attack each other.
#
# Given an integer n, return the number of distinct solutions to the n-queens
# puzzle.
#
#
# Example 1:
#
#
# Input: n = 4
# Output: 2
# Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
#
#
#
# Example 2:
#
#
# Input: n = 1
# Output: 1
#
#
#
# Constraints:
#
#
# 1 <= n <= 9
#
# Related Topics 回溯 👍 441 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def __init__(self):
self.res = 0
self.cols = set()
self.right_down = set()
self.left_down = set()
def dfs(self, cur, n):
if cur >= n:
self.res += 1
for i in range(n):
if i + cur not in self.left_down and i - cur not in self.right_down and i not in self.cols:
self.left_down.add(i + cur)
self.right_down.add(i - cur)
self.cols.add(i)
self.dfs(cur + 1, n)
self.left_down.remove(i + cur)
self.right_down.remove(i - cur)
self.cols.remove(i)
def totalNQueens(self, n: int) -> int:
self.dfs(0, n)
return self.res
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
so = Solution()
res = so.totalNQueens(4)
print(res)
1.1 解题思路
- left-down 横纵坐标的求和为定值。
- right-down 横纵坐标相减为定值。