2022年 11月 9日

从《汉诺塔》来讲递归算法

哈喽,大家好,我是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;
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

输出结果:

在这里插入图片描述

代码(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")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

输出结果:
在这里插入图片描述

哈哈