C++ recursice 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 *