首页 > 其他分享 >汉诺塔问题

汉诺塔问题

时间:2024-01-20 11:13:49浏览次数:27  
标签:柱子 plt hanoi 问题 source 汉诺塔 time

四阶汉诺塔求解图:

汉诺塔问题代码实现以及当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()

结果输出:

标签:柱子,plt,hanoi,问题,source,汉诺塔,time
From: https://www.cnblogs.com/doris510/p/17976146

相关文章

  • openeuler2203升级openssh9.4p1解决漏洞问题
    openeuler2203升级openssh9.4p1解决漏洞问题 1,使用rpmbuild将tar包打成rpm包,不喜欢编译升级的,使用RPM升级就方便多了。想使用openssh的源码包编译安装的,参考这里:OpenSSH-9.4p1(linuxfromscratch.org) 2,准备编译环境[root@centos7-31~]#  yuminstallrpm-buildzlib......
  • Visual Studio + QT环境 界面中文乱码问题及解决
    情况:  头文件开头加入预编译语句#pragmaexecution_character_set("utf-8") 效果:  参考:VS2019+qt解决中文乱码问题  ......
  • 解决 Ant TreeSelect(树选择)组件可以使用键盘选中 disabled(已禁用)项的问题
    最近在使用AntDesignVue(V3.2.20)的TreeSelect组件时发现一个问题:tree-data中部分数据的disabled属性设置为了true,选项是“禁用”状态,无法通过鼠标点击选中,但是可以通过键盘↑↓键切换选项,按下Enter键选中。一开始还以为是bug,后来通过查阅文档和测试发现,该组件还......
  • 吴师兄学算法day08 贪心 605. 种花问题
    题目:605.种花问题易错点:没想出来,借鉴了灵山的代码的思路,强行种花。我喜欢这个思路。感觉有点像设置哨兵那样的。 我的代码:classSolution:defcanPlaceFlowers(self,flowerbed:List[int],n:int)->bool:#修改数组,每次都种花,#凑够3个0......
  • 使用Nuxt框架刷新页面向后端接口请求两次的问题
    背景:当我刷新页面时,发现后端接口被请求了两次前端使用框架:nuxt、vue、axios等后端使用框架:springboot、maven、redis、mybatisplus等主页面程序代码<script>importhomePagefrom'@/api/homePage'exportdefault{data(){return{bannerList:[],//轮播......
  • 重复spin问题
    ROS2重复spin问题报错描述:在执行回调函数时,报错terminatecalledafterthrowinganinstanceof'std::runtime_error'what():Node'/workflow_control_node'hasalreadybeenaddedtoanexecutor.[ros2run]:Aborted;原因在回调函数中又执行了rclcpp::spin监听函......
  • /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.34' not found问题解决
    有一个go实现的项目代码最近有更新,自己在开发环境上手动构建并运行都没有问题(构建和运行时相同环境,肯定没有问题^_^)。后面通过jenkins构建镜像也没有问题,运行时却报错 之前的版本在jenkins上构建也是成功的,后沟通得知jenkins集群版本最近有更新 那么,大概知道原因了,由于jenk......
  • vue3 之 问题总结(一)
    Vue3官网:https://cn.vuejs.org/guide/introduction.html一、为什么要使用ref?使用ref来创建响应式数据,当你在模板中使用了一个ref,然后改变了这个ref的值时,Vue会自动检测到这个变化,并且相应地更新DOM。在标准的JavaScript中,检测普通变量的访问或修改是行......
  • telegraf解析嵌套json遇到的问题
    问题描述kafka中的数据格式如下:{"customerId":1652,"deviceId":"13011304383","timestamp":1705637828000,"parameters":{"acc":0,"locationStatus":1,&......
  • 动态规划(6) 打劫问题
    目录打家劫舍打家劫舍第一题应该不难想classSolution{public:introb(vector<int>&nums){//dp含义,偷到第n号房间最多能偷多少intn=nums.size();if(n==1){returnnums[0];}vector<int>dp(n,0);......