Description
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
Example
Input: 4
Output: [
[".Q…", // Solution 1
“…Q”,
“Q…”,
“…Q.”],
["…Q.", // Solution 2
“Q…”,
“…Q”,
“.Q…”]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
Submissions
首先明确题目要求是任意两个皇后都不能处于同一条横行、纵行或斜线上,因此总结出三种情况的特征:
1.在同一行或同一列的元素的横坐标或纵坐标相同
2.在正对角线上的元素横纵坐标的差相同,同理正对角线方向上的两个元素的横纵坐标的差也相同。
3.在斜对角线上的元素横纵坐标的和相同,同理斜对角线方向上的两个元素的横纵坐标的和也相同。
解题思路采用DFS深度优先遍历,一次深度查找直到最后一个满足或不满足条件的位置,回溯。其中遍历n代表遍历皇后的横坐标,col存储的是皇后的纵坐标,dia存储皇后的横纵坐标差,codia存储皇后的横纵坐标和。确定皇后横坐标开始深度优先遍历纵坐标,满足位置条件时则更新col,dia,codia三个列表以判断下一位置是否符合条件,当遍历到一定深度无解时则遍历下一横坐标,最后将有效解存储到rel列表中。之后利用generate函数,将rel中的有效解转换成"."和"Q"的表示形式并返回所有结果。
实现代码如下:
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
if n==0:
return []
self.rel = []
col = []
dia = []
codia = []
self.DFS(n,col,dia,codia)
return self.generate(n)
def DFS(self,n,col,dia,codia):
x = len(col)
if x == n:
self.rel.append(col)
return None
for y in range(n):
if y not in col and x-y not in dia and x+y not in codia:
self.DFS(n,col+[y],dia+[x-y],codia+[x+y])
def generate(self,n):
final_rel = []
temp = []
for i in self.rel:
for j in i:
temp.append("."*j+"Q"+"."*(n-j-1))
final_rel.append(temp)
temp = []
return final_rel