我尝试使用 BFS 用 10 个磁盘解决河内之塔(以最小的步长),您可以将磁盘放在任何您想要的位置,但它花费的时间太长并且占用太多内存。大家有什么建议吗?
对于这10个磁盘案例,我应该使用哪种算法,并且磁盘是随机启动的,您可以将磁盘放在解决过程中的任何位置?
我的代码:
class Node():
def __init__(self,matrix,parent):
self.matrix = matrix
self.parent = parent
def CreateNode(matrix,parent) -> Node:
new_mat = [nested[:] for nested in matrix]
newnode = Node(matrix,parent)
return newnode
def appender(matrix,i,query,gone,solution):
if matrix[i] != []:
for j in range(3):
if j != i:
temp = [nested[:] for nested in matrix]
temp[j].append(temp[i].pop(-1))
if ''.join(map(str,temp)) not in gone:
gone.add(''.join(map(str,temp)))
sub_solution = CreateNode(temp,solution)
query.append(sub_solution)
def printMatrix(mat):
for i in mat:
for j in i:
print(j,end=" ")
print()
print("#")
def PrintSolution(root):
if root == None:
return
PrintSolution(root.parent)
printMatrix(root.matrix)
def solver(A,list):
gone = set()
query = []
root = Node(A,None)
query.append(root)
while query:
solution = query.pop(0)
if solution.matrix[-1] == list:
PrintSolution(solution)
return
for i in range(3):
appender(solution.matrix,i,query,gone,solution)
A = []
for i in range(3):
arr = [int(i) for i in input().split()]
A.append(arr)
maxi = max(max(A))
list = []
for i in range(maxi,-1,-1):
list.append(i)
solver(A,list)
示例输入:
6 9 0 1 2
4 7
3 5 8
输出:
6 9 0 1 2
4 7
3 5 8
#
6 9 0 1 2
4 7 8
3 5
#
6 9 0 1
4 7 8
3 5 2
#
etc until solved
答案 0 :(得分:-1)
我认为这对您的情况很有帮助
def hanoi(n: int, fromPos: int, toPos: int, via: int) -> None:
if n == 1:
print("Move disk from pole %d to pole %d" % (fromPos, toPos)
else:
move(n - 1, fromPos, via, toPos)
move(1, fromPos, toPos, via)
move(n - 1, via, toPos, fromPos)