Advertisement
UrNotSorry

Towers of Hanoi

Sep 9th, 2014
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <cstdlib>   // for atoi
  2. #include <iostream>
  3.  
  4. using std::string;
  5. using std::cout;
  6. using std::endl;
  7.  
  8. void moveDisks(int height, string from, string other, string to);
  9.  
  10. int main(int argc, char *argv[]) {
  11.   if (argc != 2) {
  12.     std::cout << "Usage: " << argv[0] << " number_of_disks" << std::endl;
  13.     return -1;
  14.   }
  15.   int n = atoi(argv[1]);
  16.   moveDisks(n, "peg A", "peg B", "peg C");
  17.   return 0;
  18. }
  19.  
  20. void moveDisks(int height, string from, string other, string to) {
  21.     if (height == 1) {
  22.         cout << "Move disk from " << from << " to " << to << endl;
  23.     }
  24.     else {
  25.         moveDisks(height - 1, from, to, other);
  26.         moveDisks(1, from, other, to);
  27.         moveDisks(height - 1, other, from, to);
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement