Colleagues, please explain how the program code of the Tower of Hanoi works.
#include <iostream> #include <Windows.h> using namespace std; void Towers(int number, int from, int to, int free) { SetConsoleOutputCP(1251); if(number!=0) { Towers(number-1, from, free, to); cout<<"\n Снимаем "<<number<<"-й диск с "<<from<<"-го стержня и одеваем его на "<<to<<"-й стержень"; Towers(number-1, free, to, from); } } void main() { Towers(3, 1, 3, 2); cout<<"\n "; }
- "number" is the number of disks.
- "from" is the pivot from which we transfer all disks.
- "to" is the pivot on which we transfer all disks.
- "free" is the third pivot.
And this is the result in the console window:
Снимаем 1-й диск с 1-го стержня и одеваем его на 3-й стержень. Снимаем 2-й диск с 1-го стержня и одеваем его на 2-й стержень. Снимаем 1-й диск с 3-го стержня и одеваем его на 2-й стержень. Снимаем 3-й диск с 1-го стержня и одеваем его на 3-й стержень. Снимаем 1-й диск с 2-го стержня и одеваем его на 1-й стержень. Снимаем 2-й диск с 2-го стержня и одеваем его на 3-й стержень. Снимаем 1-й диск с 1-го стержня и одеваем его на 3-й стержень.
What I understand here is that at the beginning of the function, it immediately recursively calls itself as many times as the "if" condition is true and every time a unit is taken from the "number", comes to "number == 1", and then the first one is output line on console Then again a recursive function call, with arguments arranged in a different order and fog ...