https://leetcode.com/problems/n-queens/
https://leetcode.com/problems/n-queens-ii/
参考
递归回溯
http://www.cnblogs.com/zuoyuan/p/3747249.html
其中 还可以加上board[depth]= -1
board[depth]=i
s='.'*n
dfs(depth+1, valuelist+[s[:i]+'Q'+s[i+1:]])
board[depth]= -1 #可要可不要
class Solution:
# @return a list of lists of string
def solveNQueens(self, n):
def check(k, j): # check if the kth queen can be put in column j!
for i in range(k):
if board[i]==j or abs(k-i)==abs(j - board[i]):#这里当前点为(k, j)以及(i, board[i])
#board[i]==j就是说不能列相同
#abs(k-i)==abs(j - board[i]),不能行差等于列差,即在对角线上
return False
return True
def dfs(depth, valuelist):
if depth==n: res.append(valuelist); return
for i in range(n):
if check(depth,i):
board[depth]=i
s='.'*n
dfs(depth+1, valuelist+[s[:i]+'Q'+s[i+1:]])
board=[-1 for i in range(n)]
res=[]
dfs(0,[])
return res