程序随笔:汉诺塔

来源:互联网 发布:java驻场开发 编辑:程序博客网 时间:2024/06/07 22:31

汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。(摘自百度百科)

由此,如何通过程序,打印出把N个圆盘从a柱子移动到c柱子的整个过程呢?

输入:圆盘的个数n

输出:移动圆盘的步骤,一共需要的步骤数。

eg:

输入:3

输出:

1 is moved from a to c
2 is moved from a to b
1 is moved from c to b
3 is moved from a to c
1 is moved from b to a
2 is moved from b to c
1 is moved from a to c
hano of 3 needs 7 steps

解决思路:

1,若只有一个圆盘,只需将圆盘1从a移动到c;

2,若有两个圆盘,需要先将圆盘1从a移动到辅助塔b,再将圆盘2从a移动到c,最后将圆盘1从b移动到c;

3,若有三个圆盘,需要将(1,2)两个圆盘按序移动到辅助塔b,再将圆盘3从a移动到c,最后将(1,2)从b移动到c;

4,依此类推,若有N个圆盘,首先应该把前(N-1)个圆盘移动到辅助塔b上,随后才可以将第N个圆盘由a移动到c,接下来再以a作为辅助塔,将这(N-1)个圆盘从b移动到c;

因此,可以使用递归来实现:

int hano_action(char src, char mid, char dest, int n) {    if (n == 1) {        cout<< n <<" is moved from "<<src<<" to "<<dest<<endl;return 1;    }    int a = hano_action(src, dest, mid, n-1);    cout<<n<<" is moved from "<<src<<" to "<<dest<<endl;    int b = hano_action(mid, src, dest, n-1);    return a + b + 1;}int main(int argc, char * argv[]) {    int n = 5;    int res = hano_action('a','b','c',n);    cout<<"hano of "<<n<<" needs "<<res<<" steps."<<endl;}

昨天坐地铁的时候想到这个问题,突然想把思路记录下来,留作以后的温故知新。

0 0
原创粉丝点击