汉诺塔问题

问题描述:从左到右有A、B、C三根柱子,其中A柱子上面有从小叠到大的n个圆盘,现要求将A柱子上的圆盘移到C柱子上去,期间只有一个原则:一次只能移到一个盘子且大盘子不能在小盘子上面,求移动的步骤和移动的次数

问题解决方案:

  如果只有一个圆盘,直接从A移动到C就好了;

  如果有两个圆盘,我们分为三步:A------>B ,A-------->C,B--------->C,即可完成。

  如果有三个圆盘,我们依然分为三步:A(上面两个圆盘当作一个整体)---------->B,A-------->C,B------->C,这样我们完成了大盘的移动,接下来按照上面方法,将A整体再进行移动即可。

  ......因此,我们可以总结出,当有n个圆盘的时候,我们可以将上面n-1个圆盘当作一个整理,进行移动,这样操作就和三个圆盘情况一直。至于A這个整体,我哦没只需要进行递归处理即可。

算法:

  Js版

<script type="text/javascript">
function hanoi(n,from,to,helper){
    if (n==1) {
        console.log("move to plate from " + from + '----->' + to);
        return;
    }
    hanoi(n-1,from,helper,to); // 将A上面的n-1个盘子通过C移动到B上面
    move(from,to); //将A上面的最后一个盘子移到C上面
    hanoi(n-1,helper,from,to); //将B上面的n-1个盘子移动到C上面
}
function move(from ,to){
    console.log("move a plate from " + from + '----->' + to);
}
    hanoi(10,'A','B','C');

</script>

  C版

#include <stdlib.h>
#include <stdio.h>

void move(char from,char to){
    printf("move to plate from  %c  to %c \n" ,from ,to);
}

void hanoi(int n,char from,char helper,char to){
    if (n == 1)
    {
        printf("move to plate from  %c  to %c \n" ,from ,to);
    }
    hanoi(n-1,from,helper,to);
    move(from,to);
    hanoi(n-1,helper,from,to);
}

void main(int argc, char const *argv[])
{
    hanoi(10,'A','B','C');
    return 0;
}

  python版

def hanoi(n,fromA,helperB,toc):
    if n==1:
        print fromA + "------->" + toc
    hanoi(n-1,fromA,helperB,toc)
    move(fromA,toc)
    hanoi(n-1,helperB,fromA,toc)

def move(fromA,toc):
    print fromA + "------------>" + toc

 

posted @ 2017-08-11 14:34  看雪。  阅读(231)  评论(0)    收藏  举报