Saturday, 10 September 2011

towers of hanoi c++

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. void towers( vector <int> &disks, int start, int end, int temp)
  6. {
  7. if( disks == 1 ) // base case
  8. cout <<start <<"---> "<< end <<"\n";
  9.  
  10. else //recursion step
  11. {
  12. //move disks - 1 disk from start to temp
  13. towers(disks - 1, start, temp, end);
  14.  
  15. //move last disk from start to end
  16. cout<<start<< "---> "<< end << "\n";
  17.  
  18. //move disks - 1 disk from temp to end
  19. towers(disks - 1, temp, end, start);
  20.  
  21. } // end else
  22. } // end function towers
  23.  
  24. int main()
  25. {
  26. int n;
  27. cout<<"Enter number of Discs: ";
  28. cin >> n;
  29. towers(n, 1, 3, 2);
  30. return 0;
  31. }

No comments:

Post a Comment