(算法)Hanoi Problem汉诺塔问题

Problem:

There are three poles and N disks where each disk is heaver than the next disk. In the initial conguration, the discs are stacked upon another on the first pole where the lighter discs are above the heavier discs. We want to move all the discs to the last pole with the following conditions:

  • Only one disc can be moved from one pole to another at a time.
  • The discs have to be stacked such that all the lighter discs are on top of the heavier ones.

Recursion:

To move N discs from the first pole to the last pole, we need to move N-1 discs to the middle pole, then move the Nth disc to the last pole, and then move all N-1 discs from the middle pole back to the last pole.

Code:

#include <iostream>

using namespace std;

void hanoi(int N,int start,int helper,int destination){
if(N==1)
cout<<"Move "<<start<<" to "<<destination<<endl;
else{
hanoi(N-1,start,destination,helper);
hanoi(1,start,helper,destination);
hanoi(N-1,helper,start,destination);
}
} int main()
{
int N=10;
hanoi(10,1,2,3);
return 0;
}
上一篇:html5 audio组件禁止下载


下一篇:MySQL数据丢失讨论