C++ recursive program to solve Tower of Hanoi puzzle.

Sample Input:

In:
4
Out:
Move disk 1 from tower 0 to tower 2
Move disk 2 from tower 0 to tower 1
Move disk 1 from tower 2 to tower 1
Move disk 3 from tower 0 to tower 2
Move disk 1 from tower 1 to tower 0
Move disk 2 from tower 1 to tower 2
Move disk 1 from tower 0 to tower 2
Move disk 4 from tower 0 to tower 1
Move disk 1 from tower 2 to tower 1
Move disk 2 from tower 2 to tower 0
Move disk 1 from tower 1 to tower 0
Move disk 3 from tower 2 to tower 1
Move disk 1 from tower 0 to tower 2
Move disk 2 from tower 0 to tower 1
Move disk 1 from tower 2 to tower 1

Code:

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

#include <iostream>

using namespace std;

void solveHanoi(int discNumber, int A, int B, int C);

int main()
{
  int discNumber;

  cout << "Hanoi solver recursive algorithm" << endl;
  cout << "TheFlyingKeyboard.net 2017" << endl;
  cout << "Enter number of discs: ";
  cin >> discNumber;

  solveHanoi(discNumber, 0, 1, 2);

  int tmp;

  cin >> tmp;

  return 0;
}

void solveHanoi(int discNumber, int A, int B, int C)
{
  if (discNumber == 0)
  {
    return;
  }

  solveHanoi(discNumber - 1, A, C, B);

  cout << "Move disk " << discNumber << " from tower " << A << " to tower " << B << endl;

  solveHanoi(discNumber - 1, C, B, A);
}

 

C++ Recursive Hanoi Solver
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close