问题描述:
设计解决汉诺塔问题的程序,并给出n=2,4,8,16,32 时的执行时间
代码如下:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 11:11:00 2022
@author: Dell
"""
import time
def hanota(n,A,B,C): #定义汉诺塔函数,参数n是圆盘数,A、B、C是3根柱
if n==1:
return 0 # 直接将A柱上的圆盘移动到C柱上
else:
hanota(n-1,A,C,B) #递归将A柱最上方的n-1个盘子落在B柱
hanota(n-1,B,A,C) #递归将B柱上的n-1个盘子,落在C柱
t = time.perf_counter() #获取当前时间
hanota(2,'A','B','C')
print(f'cost(n=2):{time.perf_counter() - t:.8f}s')
t = time.perf_counter()
hanota(4,'A','B','C')
print(f'cost(n=4):{time.perf_counter() - t:.8f}s')
t = time.perf_counter()
hanota(8,'A','B','C')
print(f'cost(n=8):{time.perf_counter() - t:.8f}s')
t = time.perf_counter()
hanota(16,'A','B','C')
print(f'cost(n=16):{time.perf_counter() - t:.8f}s')
t = time.perf_counter()
hanota(32,'A','B','C')
print(f'cost(n=32):{time.perf_counter() - t:.8f}s')
这里是把每一步移动都做完了,所以时间比较长,也可以只计算移动次数,但是不去真正移动,那样n=32时花费的时间只有几秒