代码来自维基教科书:C++ Programming As A Set Of Problems。
程序如下:
#include <iostream>
void hanoi(int depth, int from, int to, int alternate)
{
if(depth == 0)
{
return;
}
hanoi(depth-1, from, alternate, to);
std::cout << "Move ring " << depth << " from pole " << from << " to pole " << to << "." << std::endl;
hanoi(depth-1, alternate, to, from);
}
int main(int argc, char** argv)
{
hanoi(4, 1, 2, 3);
return 0;
}
程序运行结果如下:
Move ring 1 from pole 1 to pole 3.
Move ring 2 from pole 1 to pole 2.
Move ring 1 from pole 3 to pole 2.
Move ring 3 from pole 1 to pole 3.
Move ring 1 from pole 2 to pole 1.
Move ring 2 from pole 2 to pole 3.
Move ring 1 from pole 1 to pole 3.
Move ring 4 from pole 1 to pole 2.
Move ring 1 from pole 3 to pole 2.
Move ring 2 from pole 3 to pole 1.
Move ring 1 from pole 2 to pole 1.
Move ring 3 from pole 3 to pole 2.
Move ring 1 from pole 1 to pole 3.
Move ring 2 from pole 1 to pole 2.
Move ring 1 from pole 3 to pole 2.