Here is simple program explaining implementation of Tower of Hanoi algorithm using recursion in C++.
First we need to know that what are the Rules of Tower of Hanoi:
- Only a single disc is allowed to be transferred at a time.
- Each transfer or move should consists of taking the upper disk from one of the stack and then placing it on the top of another stack i.e. only a top most disk on the stack can be moved.
- Larger disk cannot be placed over smaller disk; placing of disk should be in increasing order.
A, B and C are rods or pegs and n is the total number of discs, 1 is the largest disk and 5 is the smallest one.
- Move n-1 discs from rod A to B using C as intermediate rod.
- Move nth disc from A to C rod.
- Move n-1 disc from B to C using A as intermediate rod.
In the program source code, tower_fun() is a recursive function with four arguments namely n, tx, ty and tz.
Main program: When you will run the code you will see a line in console
“Enter the no. of disks::”. You need to give number of disks you want to put in in A rod at program initial time.
tower obj(no); By this line you will create an object of class tower and initialize the number of disks using variable “no”.
obj.disp_tower(); This line will call tower classes function disp_tower() and it will display initial values in A rod. Example. Let’s we give tower obj(3); then disp_tower() function will print 3, 2, 1
obj.tower_fun(no,1,2,3); This line will call tower_fun() function with four parameters and it’s our main function and recursive function.
Recursive function calls itself until the condition is true or is a potential cycle of function calls.
Download Source Code Implementation of Tower of Hanoi algorithm using recursion in C++
[sociallocker]
Download Source Code Implementation of Tower of Hanoi algorithm using recursion in C++
Password: codewithc.com
[/sociallocker]