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;
    	
    }


  • 相关阅读:
    网页Tab控件
    ivy在eclipse中的重新加载
    es删除文档或者删除索引
    es修改数据
    es中插入数据
    创建es索引-格式化和非格式化
    MySQL常用字符串函数
    python各种类型转换
    python 3.4读取输入参数
    python异常捕获异常堆栈输出
  • 原文地址:https://www.cnblogs.com/jacksin/p/8830229.html
Copyright © 2011-2022 走看看