[Lintcode]33. N-Queens/[Leetcode]51. N-Queens
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]33. N-Queens/[Leetcode]51. N-Queens相关的知识,希望对你有一定的参考价值。
33. N-Queens/51. N-Queens
- 本题难度: Medium/Hard
- Topic: Search & Recursion
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
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
别人的代码
DFS
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都可以。
注意代码的简洁美观。
- 出错
- collection.deque() 括号内是表示队列的list形式,所以千万不要少写了一个括号
- queue.popleft()不是queue.leftpop()
以上是关于[Lintcode]33. N-Queens/[Leetcode]51. N-Queens的主要内容,如果未能解决你的问题,请参考以下文章
[Lintcode]62. Search in Rotated Sorted Array/[Leetcode]33. Search in Rotated Sorted Array