皇后可以直走,横走,斜着走。
回溯法:
回溯法的意思是,在某个位置放下皇后后,发现并不符合规则,然后就把这个皇后拿起来重新放,可以理解为悔棋。
在解皇后问题时,我们需要知道的是,西洋棋牌的主对角线(hill_diagonals)和次对角线(dale_diagonals)的一个关系:
主对角线:行序号+列序号 = 常数
次对角线:行序号-列序号 = 常数
class Solution:
def solveNQueens(self, n: int):
def could_place(row, col):
return not (cols[col] + hill_diagonals[row - col] + dale_diagonals[row + col])
def place_queen(row, col):
queens.add((row, col))
cols[col] = 1
hill_diagonals[row - col] = 1
dale_diagonals[row + col] = 1
def remove_queen(row, col):
queens.remove((row, col))
cols[col] = 0
hill_diagonals[row - col] = 0
dale_diagonals[row + col] = 0
def add_solution():
solution = []
temp = sorted(queens)
for _, col in temp:
solution.append('.' * col + 'Q' + '.' * (n - col - 1))
output.append(solution)
def backtrack(row=0):
for col in range(n):
if could_place(row, col):
place_queen(row, col)
if row + 1 == n:
add_solution()
else:
backtrack(row + 1)
remove_queen(row, col)
cols = [0] * n
hill_diagonals = [0] * (2 * n - 1)
dale_diagonals = [0] * (2 * n - 1)
queens = set()
output = []
backtrack()
return output
n = 4
s = Solution().solveNQueens(n)
for i in s:
print(i)
'''output:
['.Q..', '...Q', 'Q...', '..Q.']
['..Q.', 'Q...', '...Q', '.Q..']
'''
来源:CSDN
作者:ZJE_ANDY
链接:https://blog.csdn.net/u014453898/article/details/104596472