标签:return do it hat == ica abs 一个 val The
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
Example 1:
Input:1
Output:
[["Q"]]
Example 2:
Input:4
Output:
[
// Solution 1
[".Q..",
"...Q",
"Q...",
"..Q."
],
// Solution 2
["..Q.",
"Q...",
"...Q",
".Q.."
]]
Challenge
Can you do it without recursion?
class Solution:
def solveNQueens(self, n: ‘int‘) -> ‘List[List[str]]‘:
#dfs
res = []
queue = collections.deque([[]])
while(queue):
tmp = queue.popleft()
if len(tmp) == n:
res.append(tmp)
else:
for i in range(n):
if self.isValid(tmp,i):
queue.append(tmp+[i])
return self.getTable(res,n)
def isValid(self,path,nextStep):
#nextStep l
l = len(path)
for i in range(l):
if path[i] == nextStep or (l-i == abs(path[i]-nextStep)):
return False
return True
def getTable(self,res,n):
#res = [[2,0,3,1],[1,3,0,2]]
#table = ..
table = []
for solution_i in res:
table_i = []
for pos_i in solution_i:
col = ‘.‘*n
table_i.append(col[:pos_i]+‘Q‘+col[pos_i+1:])
table.append(table_i)
return table
import collections
class Solution:
"""
@param: n: The number of queens
@return: All distinct solutions
"""
def solveNQueens(self, n):
# write your code here
#DFS
res = []
self.dfs([-1]*n,[],0,res,n)
return res
def dfs(self,plist,path,index,res,n):
if index == n:
res.append(path)
return
for i in range(n):
plist[index] = i
if self.valid(plist,index):
tmp = ‘.‘*n
self.dfs(plist,path+[tmp[:i]+‘Q‘+tmp[i+1:]],index+1,res,n)
def valid(self,plist,index):
for i in range(index):
if plist[i] == plist[index] or index-i == abs(plist[index]-plist[i]):
return False
return True
思路
经典的题目,DFS和BFS都可以。
注意代码的简洁美观。
[Lintcode]33. N-Queens/[Leetcode]51. N-Queens
标签:return do it hat == ica abs 一个 val The
原文地址:https://www.cnblogs.com/siriusli/p/10386191.html