zoukankan      html  css  js  c++  java
  • [Python]递归汉诺塔

    move_count  =  0 ; 
    def hanoi(n,src,buffer,dst):
        'n:需移动的盘子个数,src:盘子原来的位置,buffer:盘子可临时使用的位置,dst:盘子的目标移动位置'
        global move_count;
        if n < 1:
            print('输入有误');
            return None;
        elif n==1:
            print(src + '----->' + dst);
            move_count += 1;
        else:
            hanoi(n-1,src,dst,buffer);
            hanoi(1,src,buffer,dst);
            hanoi(n-1,buffer,src,dst);
    
    
    move_count  = 0 ;
    hanoi(5,'A','B','C');
    print('move_steps = ',move_count);
    print(hanoi.__doc__);

      

    运行结果(Python3.7):

    A----->C
    A----->B
    C----->B
    A----->C
    B----->A
    B----->C
    A----->C
    A----->B
    C----->B
    C----->A
    B----->A
    C----->B
    A----->C
    A----->B
    C----->B
    A----->C
    B----->A
    B----->C
    A----->C
    B----->A
    C----->B
    C----->A
    B----->A
    B----->C
    A----->C
    A----->B
    C----->B
    A----->C
    B----->A
    B----->C
    A----->C
    move_steps = 31
    n:需移动的盘子个数,src:盘子原来的位置,buffer:盘子可临时使用的位置,dst:盘子的目标移动位置

    ~不再更新,都不让我写公式,博客园太拉胯了
  • 相关阅读:
    课下作业--微软拼音输入法评价
    课堂练习--找水王
    第十四周总结
    第一阶段意见评论
    第十三周总结
    梦断代码阅读笔记03
    第十二周总结
    用户模板与用户场景
    2020年寒假假期总结0205
    2020年寒假假期总结0204
  • 原文地址:https://www.cnblogs.com/alimy/p/10373071.html
Copyright © 2011-2022 走看看