n皇后问题
n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
思路:递归
代码
class nQueen():
def __init__(self,n): # 输入n
self.n = n
record = [0] * n
num = self.process(0,record)
print("总次数:",num) # 总次数
# 当前位置(i,j)能否放皇后
def isValid(self,record,i,j):
for k in range(i): #
if j == record[k] or abs(record[k] - j) == abs(i - k):
return False
return True
# 递归过程
def process(self,row,record):
if row == self.n: # 找到了一个可行结果
print("一种方式:",record)
return 1
res = 0
for j in range(self.n):
if self.isValid(record,row,j):
record[row] = j
res += self.process(row+1,record)
return res
nQueen(6) # 在这里改变N
简洁代码:
def solveNQueens(self, n: int) -> List[List[str]]:
rn = []
col = [0] *n
def dfs(r,s):
if r == n:
rn.append(['.'*c+'Q'+'.'*(n-1-c) for c in col])
for c in s:
if all(r+c != R+col[R] and r-c != R-col[R] for R in range(r)):
col[r] = c
dfs(r+1,s-{c})
dfs(0,set(range(n)))
return rn
solveNQueens(6)
汉诺塔问题
思路:分治
将n个盘子从左拿到右,分为3个步骤
- 将n-1个盘子,先一起拿到中间
- 将第n个最大的盘子,直接拿到最右边
- 将n-1个盘子,从中间拿到最右边
代码
# 从start到end ,可以使用的是other
def fun(i,start,end,other):
if i == 1:
print("move 1 from",start,"to",end)
else:
fun(i-1,start,other,end) # 先把i-1个从start拿到other,
print("move",i,"from",start,'to',end) # i个拿到end位置
fun(i-1,other,end,start) # 再把i-1个从other拿到end
fun(3,'左','右','中')