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 the number of distinct solutions to the n-queens puzzle.
Example
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q…", // Solution 1
“…Q”,
“Q…”,
“…Q.”],
["…Q.", // Solution 2
“Q…”,
“…Q”,
“.Q…”]
]
Submissions
首先这道题要求给定一个整数 n,返回 n 皇后不同的解决方案的数量,题目基本与上一题相同,所以重点解题思路可看上篇博客,同理这道题解题思路一样采用DFS深度优先遍历,一次深度查找直到最后一个满足或不满足条件的位置,回溯。其中遍历n代表遍历皇后的横坐标,col存储的是皇后的纵坐标,dia存储皇后的横纵坐标差,codia存储皇后的横纵坐标和。确定皇后横坐标开始深度优先遍历纵坐标,满足位置条件时则更新col,dia,codia三个列表以判断下一位置是否符合条件,当遍历到一定深度无解时则遍历下一横坐标,最后将有效解存储到rel列表中并返回结果个数。
实现代码如下:
class Solution:
def totalNQueens(self, n: int) -> int:
if n==0:
return []
self.rel = []
col = []
dia = []
codia = []
self.DFS(n,col,dia,codia)
return len(self.rel)
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])