栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

数据结构与算法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构与算法

Day 1: Hanoi problem

  1. History Background

According to the history of India culture, about thousands of years ago, in the process of Brahma creating the world, he set 3 columns which called 'A', 'B' and 'C'. In addition to these columns, there existed 64 rings putting on the column ‘A’ that their sizes were different and they were set from large to small.

Brahma said that the world will be destroyed as long as these 64 rings all transport from 'A' to the other one column in a particular principle that the small ring can't put under a larger one.

  1. Requirement

So, in this part, we, general humans, need to program coding to Express concrete processes of the requirement of Brahma and achieving his aim.

  1. Personal comprehension and the emphasis of habits of programming

   1编码习惯强调:在写代码之前一定要写思路!

2个人理解:对于这一题,最重要的部分就是去理解递归的底层逻辑。

对递归而言,最重要的有三个部分:

1°递归的终止条件

2°可以考虑使用逆向思维,只要考虑最后一层的步骤即可。

3°递归最后一层和上一层之间的联系如何使用非递归方式去表达。

对于整个过程的最后一步:我们将这n个圆环分成上层的n-1个和最下层的1个这两个部分。正向思路是:

1将上方n-1个圆盘从A经过C移动到B

2然后再把最后一个最大圆盘从A直接移动到C

3再把n-1个圆环从B经过A移动到C

2°从最后一步推出上一步(逆向思路):递归的最后一步一定是把上层n-1个圆盘从B经过A移动到C(因为此时最底的圆盘必须处在C,所以之前我们必须要将上方的n-1个圆盘移开,即:从A经过C移动到B, 之后就是最底的圆盘从A直接移动到C),那么经过这样的分析,逆向思路和正向思路就一致了,这也是一种方法。

递归终止条件:圆盘都没了,就不用搬运了。


Python代码:

def hanoi(n, a, b, c):
    if n > 0 :
        hanoi(n-1, a, c, b)
        print("%c -> %c"%(a,c))
        hanoi(n-1, b, a, c)

hanoi(1,'a','b','c')

C代码

#include 
void hanoi(int n, char a, char b, char c)
{
	if(n > 0)
	{
		hanoi(n-1,a,c,b);
		printf("%c -> %cn",a,c);
		hanoi(n-1,b,a,c);
	};
}
int main()
{
    hanoi(3,'a','b','c');
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/928497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号