算法分析之汉诺塔问题

#include <iostream>
using namespace std;
void move(char from ,char to) {
      cout<<"Move"<<from<<"to"<<to<<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 diskes:";
    cin>>m;
    cout<<"move"<<m<<"diskes:\n";
    hanoi(m,'A','B','C');
}

运行结果:

 

 

number = 3

 

 

 

number = 13

 

 

 

 

 

可以看出随着盘子数量的增加,运行时间也随之增加。

posted @ 2019-09-25 10:57  laucheng  阅读(491)  评论(0编辑  收藏  举报