汉诺塔

来源:互联网 发布:淘宝刷钻最新方法 编辑:程序博客网 时间:2024/05/16 08:32

Problem

Only one disk may be moved at a time.
Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
No disk may be placed on top of a smaller disk.

Solution

#include <iostream>#include <stack>using namespace std;void hanio_tower(int n, char src, char bridge, char dst){    if(n == 0){        return;    }    if(n == 1){        cout << "move " << n << " from " << src << " to " << dst << endl;        return;    }    else{        hanio_tower(n - 1, src, dst, bridge);        cout << "move " << n << " from " << src << " to " << dst << endl;        hanio_tower(n - 1, bridge, src, dst);    }}int main(int argc, char* argv[]){    hanio_tower(3, 'a', 'b', 'c');     return 0;}

Output

move 1 from a to bmove 2 from a to cmove 1 from b to cmove 3 from a to bmove 1 from c to amove 2 from c to bmove 1 from a to bmove 4 from a to cmove 1 from b to cmove 2 from b to amove 1 from c to amove 3 from b to cmove 1 from a to bmove 2 from a to cmove 1 from b to c


原创粉丝点击