无论是用何种语言实现汉诺塔问题,其求解问题的核心算法和步骤还是大致相同的,下面总结了分别用JAVA/Python/C++ 实现汉诺塔问题的求解过程的代码和显示效果,可以体会一下不同语言下求解汉诺塔问题风格,下面我们来一起看一下吧。
C++实现汉诺塔问题求解
#include<iostream>
using namespace std;
void move(char start,char end)
{
cout<<"move"<<start<<"to"<<end<<endl;
}
void hanoi(int n,char first,char second,char third)
{
if(n==1)
move(first,third);
else{
hanoi(n-1,first,third,second);
move(first,third);
hanoi(n-1,second,first,third);
}
}
int main()
{
int m;
cout<<"the number of disks:";
cin>>m;
cout<<"move"<<m<<"diskes:\n";
hanoi(m,'A','B','C');
}
举例2个盘子显示效果
举例3个盘子显示效果
Python实现汉诺塔问题求解
def move(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
move(n-1, a, c, b)
print(a, '-->', c)
move(n-1, b, a, c)
n = input('the number of disks:')
move(int(n), 'A', 'B', 'C')
举例2个盘子显示效果
举例3个盘子显示效果
Java实现汉诺塔问题求解
package test;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int m;
System.out.print("the number of disks:");
m=scan.nextInt();
System.out.print("move"+m+"diskes:\n");
hanoi(m,'A','B','C');
}
public static void move(char start,char end)
{
System.out.print(start+"--->"+end+'\n');
}
public static void hanoi(int n,char first,char second,char third)
{
if(n==1)
move(first,third);
else{
hanoi(n-1,first,third,second);
move(first,third);
hanoi(n-1,second,first,third);
}
}
举例2个盘子显示效果
举例3个盘子显示效果
- 完成任务