51.N皇后
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。
示例:
输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
根据《python基础教程第三版》利用生成器可以解决这个问题。
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def conflict(state,nextX):
'''
检测是否有冲突
'''
nextY = len(state)
for i in range(nextY):
if abs(nextX-state[i]) in (0,nextY-i):
return True
return False
def quenes(num=8,state=()):
'''
生成一个元素是包含n皇后位置的元组的迭代器
'''
for pos in range(num):
if not conflict(state,pos):
if len(state) == num-1:
yield (pos,)
else:
for result in quenes(num,state+(pos,)):
yield (pos,) + result
def prettyprint(solution):
'''
对于一个可行路线按照标准输出
'''
def line(pos,length=len(list(solution))):
return '.'*(pos) + 'Q' + '.'*(length-pos-1)
pic = []
for pos in solution:
pic.append(line(pos))
return pic
def prettyprintall(solutions):
'''
将所有可行路线按照标准输出
'''
pic = []
for solution in solutions:
pic.append(prettyprint(solution))
return pic
return prettyprintall(quenes(n))