zoukankan      html  css  js  c++  java
  • 汉诺塔问题

    大一的时候学C语言时,在递归部分讲过汉诺塔问题,但那时只是勉强懂了而已,没有上机实验,在三年后,终于重新拾起了这个问题,并且写了程序跑了跑,不错,感觉挺清楚了。也更加地理解了递归:

    现在总结一下:


        要 将柱A的n个盘子通过柱B全部移到柱C:

           步骤可拆分下:
    1.     将柱A上面n-1个盘子通过柱C全部移到柱B;
    2.     将柱A上1的第n个盘子直接移动到C
    3.     将柱B上面n-1个盘子通过柱A全部移到柱C;
    完成上面3部就可以完成任务
    代码如下:
    #include<stdio.h>
    /*
    	Name: tower of Hanoi
    	Copyright: 
    	Author: demosees
    	Date: 22/03/17 22:00
    	Description: transfer n dishes from 1 to 3 via 2 with 1 dish a time.the big dish
    	             must always be under the small;
    	
    */
    
    void Move(int n,int start,int temp,int goal)/*solved by recursion*/ 
    {
    	/*termination condition*/ 
    	if (n==1)                
    	printf("Move disk  %d from %d to %d
    ",n,start,goal);
    	else
    {
    		Move(n-1,start,goal,temp);/*transfer n-1 form 1 to 2 via 3*/
    		printf("Move disk  %d from %d to %d
    ",n,start,goal);/*transfer the n"th" from 1 to 3*/ 
    		Move(n-1,temp,start,goal);/*transfer n-1 form 2 to 3 via 1*/
    	}
    }
    int main()
    {
    	int n;
    	/*input the number  of dishes*/ 
    	scanf("%d",&n); 
    	/*call the function*/
    	Move(n,1,2,3);
    	return 0;
    	
    }


  • 相关阅读:
    SOJ 2785_Binary Partitions
    Codeforces Round #328 (Div. 2)
    C++ fill 和memset
    SOJ 2749_The Fewest Coins
    Codeforces Round #327 (Div. 2)
    TYVJ P1013 找啊找啊找GF Label:动态规划
    TYVJ 1014 乘法游戏
    TYVJ 1011 NOIP 2008&&NOIP 2000 传纸条&&方格取数 Label:多线程dp
    错误集合
    TYVJ P1038/P1039 忠诚 标签:线段树
  • 原文地址:https://www.cnblogs.com/jacksin/p/8830229.html
Copyright © 2011-2022 走看看