![]() ![]() Moving Nth disc from tower A to tower B.Ĭout<< "\t\tMove disc " << N << " from " << source <<" to "<< dest <<"\n" TowerofHanoi(N - 1, source, dest, inter) Moving N - 1 discs from tower A to tower C. void towerOfHanoi(int N, char source, char inter, char dest)Ĭout<< "\t\tMove Disc 1 from " << source << " to " << dest << "\n" Now again, recursively call the function’ towerOfHanoi()’ for N – 1 discs to move them from ‘inter’ to ‘dest.’īelow is the code snippet for the same approach for your reference.Move the Nth disc from ‘source’ to ‘dest.’.Else recursively call the function’ towerOfHanoi()’ for N – 1 discs to move them from ‘source’ to ‘inter.’.Design a base Case for the solution as if ‘discs’ = 1, then move it from ‘source’ to ‘dest.’.Create a function, let’s say towerOfHanoi() with integer variable ‘N’ representing the number of discs, three-character variables, say ‘source,’ ‘dest’ and ‘inter’ representing source, destination, and intermediate positions.Now recursively move ‘N – 1’ discs from tower C to tower B.Īfter going through the discussion on the Algorithm above, you can try to write the recursive code by following the below-mentioned steps:.Move the ‘Nth’ disc from tower A to tower B.Recursively, move top’ N – 1′ discs from tower A to tower C.Now let us derive the general solution for the ‘N’ number of discs. ![]() We can see that 7 moves will be required to shift 3 Discs from tower A to tower B with the help of an intermediary tower C.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |