汉诺塔问题

四阶汉诺塔求解图:

汉诺塔问题代码实现以及当n=5,10,15,20增大时,算法所用时间长短变化情况图像绘制:

 1 import time
 2 import matplotlib.pyplot as plt
 3 
 4 def hanoi(n, source, target, auxiliary):
 5 if n > 0:
 6 # 将n-1个盘子从源柱子移动到辅助柱子
 7 hanoi(n - 1, source, auxiliary, target)
 8 # 将最大的盘子从源柱子移动到目标柱子
 9 print('Move disk {} from {} to {}'.format(n, source, target))
10 # 将n-1个盘子从辅助柱子移动到目标柱子
11 hanoi(n - 1, auxiliary, target, source)
12 
13 
14 def hanoi_time(n):
15 start_time = time.time()
16 hanoi(n, 'A', 'B', 'C')
17 end_time = time.time()
18 return end_time - start_time
19 
20 n_values = [5,10,15,20]
21 times = [hanoi_time(n) for n in n_values]
22 
23 
24 plt.plot(n_values, times)
25 plt.xlabel('Number of disks (n)')
26 plt.ylabel('Execution time (seconds)')
27 plt.title('Execution time of the Hanoi Tower algorithm')
28 plt.show()

结果输出:

posted @ 2024-01-20 10:58  棒打鲜橙不加冰  阅读(6)  评论(0编辑  收藏  举报