码迷,mamicode.com
首页 > 其他好文 > 详细

水题 第四站 HDU 汉诺塔VII

时间:2017-07-11 15:54:55      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:bottom   clu   art   depend   思路   lock   end   ring   汉诺塔   

先来回忆一下汉诺塔

A,B,C,三个塔将A塔上的n块砖转移到C塔,首先将(n-1)块砖转移到B塔,将第n块砖转移到C塔,再将B塔上的(n-1)块砖转移到C塔,所以

函数为借助B塔,将A塔的砖转移到C塔,

首先是借助C塔,将A塔的砖转移到B塔,

然后是借助A塔,将B塔的砖转移到C塔。

附上网上的代码,有助于理解,出处

http://blog.csdn.net/kkkkkxiaofei/article/details/8333644/

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <math.h>
 4 #include <algorithm>
 5 #include <string.h>
 6 using namespace std;
 7 int i=1;
 8 void move(int n, char from, char to)
 9 {
10     printf("第%d步:将%d号盘子%c--->%c\n",i++,n,from,to);
11 }
12 void hanoi(int n,char from,char depend_on, char to)
13 {
14     if(n==1)
15     {
16         move(1,from,to);
17     }
18     else
19     {
20         hanoi(n-1,from,to,depend_on);
21         move(n,from,to);
22         hanoi(n-1,depend_on,from,to);
23     }
24 }
25 int main ()
26 {
27     int n;
28     printf("输入盘子的个数:\n");
29     scanf("%d",&n);
30     char x=A,y=B,z=C;
31     printf("盘子的移动情况如下:\n");
32     hanoi(n,x,y,z);
33     return 0;
34 }

然后这个题目的解题思路是

1.如果第n个盘在A柱上,那么前n-1个盘处于从A柱经过C柱移向B的过程,因此第n-1个盘不可能出现在C柱。
2.如果第n个盘在C柱上,那么前n-1个盘处于从B柱经过A柱移向C的过程,因此第n-1个盘不可能出现在A柱。
 
代码还没看懂 = =

 

水题 第四站 HDU 汉诺塔VII

标签:bottom   clu   art   depend   思路   lock   end   ring   汉诺塔   

原文地址:http://www.cnblogs.com/JiaoZha/p/7150635.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!