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.
题意的要求简单来说就是在一个8*8的棋盘上摆上8个棋子,使它们不在同一行、同一列、同一斜线上。这题是一个很经典的问题。难点在问题的描述。这里我们使用一个数组board,board中元素下标代表第几行,元素值board[i]代表第i行Queen摆放的位置。下面来看这三个约束条件:
1.不同行:这个自然满足,数组board下标不同
2不同列:这个只要使board中各元素值不相同就行了。即board[i]!=board[j]
3.不同斜线:这个只要使board中元素相应的横纵坐标差的绝对值不等就行了。即|board[i]-board[j]|!=|i-j|
下面利用深度搜索即可。
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
def check(k,j):
for i in range(k):
if board[i]==j or abs(board[i]-j)==abs(k-i):
#Line 9: NameError: global name 'borad' is not defined 这个是为啥啊 拼写错误
#相应|X1-X2|=|Y1-Y2|
return False
return True
def dfs(depth,valuelist):
if depth == n:
res.append(valuelist)
return
else:
for i in range(n):
if check(depth,i):
board[depth]=i
s='.'*n
dfs(depth+1,valuelist+[s[:i]+'Q'+s[i+1:]])
res=[]
board = [-1 for i in range(n)]
dfs(0,[])
return res