"""
设计:Python程序设计
作者:初学者
日期:2022年 04月 16日
"""
# 例102 n的皇后问题
# 1.问题描述
# 根据n皇后问题,返回n皇后不同解决方案的数量,而不是具体的放置布局。
# 2.问题示例
# 输入=4,输出2,两种方案如下。
# 第一种方案:
# 0010
# 1000
# 0001
# 0100
# 第二种方案:
# 0100
# 0001
# 1000
# 0010
# 3.代码实现
class Solution:
"""
参数n:皇后的数量
返回值:不同解的总数
"""
total = 0
n = 0
def __init__(self):
self.cols = None
def queen(self, row, col):
for c, r in self.cols.items():
if c - r == col - row or c + r == col + row:
return True
return False
def search(self, row):
if row == self.n:
self.total += 1
return
for col in range(self.n):
if col in self.cols:
continue
if self.queen(row, col):
continue
self.cols[col] = row
self.search(row + 1)
del self.cols[col]
def totals(self, n):
self.n = n
self.cols = {}
self.search(0)
return self.total
# 主函数
if __name__ == '__main__':
s = Solution()
s1 = Solution()
s.totals(4)
s1.totals(8)
print("输入:", s.n)
print("输入:", s1.n)
print("输出:", s.total)
print("输出:", s1.total)
n的皇后问题
于 2022-04-16 21:04:28 首次发布