现在有三个杆子(A,B,C),在A杆自下而上,从大到小放3个圆盘。
目标:把A标上的圆盘全部移动到C盘上,并保证原有顺序。
要求:一次只能挪动一只盘子,并且不能大盘子在上,小盘子在下。
要移动2^n-1次
下图代码实现为
//把m减一个盘子,从初始位置通过three移动到two
hanoi(m - 1, one, three, two);
move(one, three);
下图代码实现为
//最后将m-1个盘子从two通过one移动到three
hanoi(m - 1, two, one, three);
以下是实现代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
void move(char x, char y)
{
printf("%c-->%c\n",x,y);
}
// m 代表盘子数
// one 起始位置
// two 中转位置
// three 目的位置
void hanoi(int m, char one, char two, char three)
{
//当就一个盘子时,直接就起始位置移动到目的位置
if (m == 1)
{
move(one, three);
}
else
{
//把m减一个盘子,从初始位置通过three移动到two
hanoi(m - 1, one, three, two);
move(one, three);
//最后将m-1个盘子从two通过one移动到three
hanoi(m - 1, two, one, three);
}
}
int main()
{
int x = 0;
scanf("%d",&x);
hanoi(x, 'A', 'B', 'C');
return 0;
}
青蛙跳台阶问题
一只青蛙要跳上n层高的台阶,一次能跳一阶,也可以跳2阶,请问这只青蛙跳上n层高的台阶有多少种跳法?
int Jump(int n)
{
int a = 1;
int b = 1;
int c = 1;
while (n >= 2) {
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int a = 0;
scanf("%d", &a);
int fb = Jump(a);
printf("青蛙跳到第%d层台阶有%d种方法", a,fb);
return 0;
}
其实本质就是斐波那契数列