Hi I am a new programmer in C++, and i am working with the recursion in Tower of Hanoi. May somebody explain for me how this code works? Much appreciated.
#include <iostream>
using namespace std;
int counter = 0;
void solveTowers(char src, char dst, char mid, int n);
int main()
{
solveTowers('A', 'C', 'B', 3);
return 0;
}
void solveTowers(char src, char dst, char mid, int n)
{
if (n == 0)
{
return;
}
solveTowers(src, mid, dst, n-1);
cout << "Move " << ++counter << ": disk " << n << " from " << src << " to " << dst << endl;
solveTowers(mid, dst, src, n-1);
}
Sure, you call the function solveTowers in the main function and the last parameter you pass is the amount of blocks on the tower, 3 in your case (google tower of hanoi)
The Function then stops if n is 0, sure, if you have no blocks to sort then you don't have to do anything.
If n is not 0 it calls itself (twice) and decreases n by 1
This algorithm is probably made by a smart person so i can't tell you why exactly and how it solves the puzzle (I never saw the puzzle before) but the part where the function calls itself is called "recursion"