哈喽,大家好,我是Tony:
这篇博客将以《汉诺塔》为例进行递归编程:
编程题
给定一个整数n,代表汉诺塔游戏中从小到大放置的n个圆盘,假设开始时所有的圆盘都放到左边的桌子上,想按照汉诺塔游戏规则把所有的圆盘都移到右边的柱子上。实现函数打印最优移动轨迹
举例
n=1时,打印:
move from left to right
n=2时,打印:
move from left to mid
move from left to right
move from mid to right
说明
这是一个典型的汉若塔问题,汉若塔问题永远都是经典的三步走:
- 把n-1的盘子移动到缓冲区
- 把1号从起点移到终点
- 把缓冲区的n-1号盘子移动到终点
代码(C++):
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//汉诺塔问题
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void funoi2(int n, string from, string buffer, string to)
{
if (n==1)
{
cout <<"Move "<<"from "<<from<<" "<< "to "<<to<<endl;
}
else
{
funoi2(n - 1, from, to, buffer);
funoi2(1, from, buffer, to);
funoi2(n - 1, buffer, from, to);
}
}
void hanoi(int n)
{
if (n <=0)
{
cout << "Error!" << endl;
}
funoi2(n,"left"," mid", "right");
}
int _tmain(int argc, _TCHAR* argv[])
{
int n=2;
hanoi(n);
return 0;
}
输出结果:
代码(Python):
def hanoi(n,from1,buffer,to):
if n==1:
print("Move",n,"from",from1,"to",to)
else:
hanoi(n-1,from1,to,buffer)
hanoi(1,from1,buffer,to)
hanoi(n-1,buffer,from1,to)
if __name__=='__main__':
hanoi(2,"left","mid","right")
输出结果:
来源:CSDN
作者:云帆之路Tony
链接:https://blog.csdn.net/weixin_42036617/article/details/104286233