'''
利用回溯算法求解八皇后问题
'''
class FindQueen:
def __init__(self):
self.total = 0 # 八皇后解的个数
self.table = [[0 for i in range(8)] for i in range(8)] # 8 x 8 的棋盘
def findQueen(self, row):
if row > 7: # 八皇后问题有解了(已经排到了第9行)
self.total += 1
self.printQueen()
return
for coloumn in range(8):
if self.check(row, coloumn):
self.table[row][coloumn] = 1
self.findQueen(row+1)
self.table[row][coloumn] = 0 # 每趟递归退出后都需将这趟递归每行置1的位置清零
def check(self, row, col):
for n in range(8): # 检查行列两个方向的有效性
if self.table[n][col] or self.table[row][n]:
return False
# 检查左对角线
lf = [self.table[row+i][col+j] for i,j in zip(range(-7,8),range(7,-8,-1)) \
if 0 <= row+i < 8 and 0 <= col+j < 8 and self.table[row+i][col+j]==1]
if len(lf):
return False
# 检查右对角线
rt = [self.table[row+i][col+j] for i,j in zip(range(-7,8),range(-7,8)) \
if 0 <= row+i < 8 and 0 <= col+j < 8 and self.table[row+i][col+j]==1]
if len(rt):
return False
return True
def printQueen(self):
for val in self.table:
print(val)
print('\n')
solutions = FindQueen()
solutions.findQueen(0)
print(solutions.total)
1.2 python利用回溯算法求解 0-1 背包问题
def bag01(N, V, C, W):
'''
:param N:N件物品
:param V:Value数组,对应每件物品的价值
:param C:Capacity,指背包的最大容量
:param W:Weight数组,对应每件物品的重量
'''
bestResult = [0] * N; curResult = [0] * N
curCost = 0; curValue = 0; bestValue = 0
def backtracking(depth):
nonlocal curCost,curValue,bestValue
if depth > N-1:
if curValue > bestValue:
bestValue = curValue
bestResult[:] = curResult[:]
print(bestResult)
print(bestValue)
else:
for i in [0, 1]: # 取或不取这件物品
curResult[depth] = i
if i == 0: # 不取这件物品
backtracking(depth+1)
else:
if curCost + W[depth] <= C:
curCost += W[depth]
curValue += V[depth]
backtracking(depth+1)
# 往上回溯,恢复现场
curCost -= W[depth]
curVal