鸿 网 互 联 www.68idc.cn

当前位置 : 服务器租用 > 编程语言开发 > c++ > >

汉诺塔问题

来源:互联网 作者:佚名 时间:2016-06-06 10:05
《C++程序设计》(梁勇著第三版558页) 无 #include iostreamusing namespace std;// The function for finding the solution to move n disks// from fromTower to toTower with auxTower void moveDisks(int n, char fromTower, char toTower, char auxTowe
《C++程序设计》(梁勇著第三版558页) <无>
#include <iostream>
using namespace std;

// The function for finding the solution to move n disks
// from fromTower to toTower with auxTower 
void moveDisks(int n, char fromTower,
    char toTower, char auxTower)
{
  if (n == 1) // Stopping condition
    cout << "Move disk " << n << " from " <<
      fromTower << " to " << toTower << endl;
  else
  {
    moveDisks(n - 1, fromTower, auxTower, toTower);
    cout << "Move disk " << n << " from " <<
      fromTower << " to " << toTower << endl;
    moveDisks(n - 1, auxTower, toTower, fromTower);
  }
}

int main()
{
  // Read number of disks, n
  cout << "Enter number of disks: ";
  int n;
  cin >> n;

  // Find the solution recursively
  cout << "The moves are: " << endl;
  moveDisks(n, 'A', 'B', 'C');

  return 0;
}
网友评论
<