Let’s understand the transfer_disk() function first to see how we have implemented the valid transfer of disks. We create three integer stacks named s,a and d(source, auxiliary and destination poles) and take the input n, for the number of disks. While(i to implement stack in this problem. Now that you have understood the approach, let’s take a look at the code to understand how exactly stack implementation of Tower of Hanoi takes place- #include It is not possible to place a larger disk on top of a smaller disk. Std::to_address in C++ with example C++ Program: Tower of Hanoi using stackĪn important point that we have to consider while writing our code is that this transfer should be a valid transfer i.e. This implies that we can iteratively implement Tower of Hanoi using stacks in C++. Similarly for n being an even number the 3 transfers being repeated in an order are-ġ) First transfer between source and destination poleĢ) Second transfer between source and auxiliary poleģ) Third transfer between destination and auxiliary pole We notice that for n being an even number, there are 3 transfers being repeated in an order-ġ) First transfer between source and auxiliary poleĢ) Second transfer between source and destination poleģ) Third transfer between auxiliary and destination pole The second step is to make two cases, one for n being an even number and the other for n being an odd number. So we notice that for a number of disks, n, it takes us 2^n-1 steps. Similarly, If we solve for n=3, we find that it takes 7 steps to move all three disks from the source. Solving for n=2, first we move disk 1 from the source to the auxiliary pole, then disk 2 from the source to the destination pole and at last disk 1 from the auxiliary to the destination pole taking us a total of 3 steps. The way to go about this problem is to first take examples with n being a very small number. The problem and the goal for n=3 looks like this The objective is to move the disks from the source pole to the destination pole according to the following rules-Ģ) You cannot place a larger disk on top of a smaller disk. the disk numbered 1(smallest disk) is on the top of the stack. The disks are first on the source pole in a descending order from bottom to top i.e. The size of the disk is directly proportional to the number on it and the three poles are known as source pole, auxiliary pole and destination pole. Tower of Hanoi is a very famous puzzle that involves disks numbered from 1 to a number n and three poles. Let’s first understand the problem and it’s rules. In this tutorial, we will learn how to solve Tower of Hanoi using stack in C++.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |