数据结构与算法

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 <stdio.h>
void hanoi(int n, char a, char b, char c)
{
	if(n > 0)
	{
		hanoi(n-1,a,c,b);
		printf("%c -> %c\n",a,c);
		hanoi(n-1,b,a,c);
	};
}
int main()
{
    hanoi(3,'a','b','c');
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值