Yes, by considering 3rd(last) disk as 1 unit and above 2 disk (Disk 1 and Disk 2) as 1 unit, (2 disk tower because we already know how to solve 2 disk tower.) Let's see how it works in case of 3 disks.Ĭan we make 3 disk tower to 2 disk tower logically Destination Peg to which the disk should be moved, Auxiliary Peg which will be helper peg for performing operation.Ĥ. Source Peg from where the disk need to be moved,ģ. That is, we will write a recursive function that takes below parameter,Ģ. In our Towers of Hanoi problem, If there is more then 2 disk, then recurse on the disk until only one disk is remaining. We already know how to solve problem with 2 disk. If we have 3 disk, we will first break down it into 2 disk (and further narrow it down to 1 disk) using recursion. Note:In general we can say, for 2 disks, it requires minimum 3 Steps to move disks from any source peg to any destination peg. this say, for moving 2 disk from Peg A to Peg B, it requires 3 steps. Scanner scanner = new Scanner(System.in) ![]() Public static final String SPARE_PEG = "Spare" Public static final String TARGET_PEG = "Target" ![]() Public static final String SOURCE_PEG = "Source" Towers of Hanoi solution source code in Java The program will print the moves of the towers of Hanoi solution in the console. The following Java program uses the above recursive strategy to solve Towers of Hanoi puzzle. The termination condition for recursion will be n=1. The first step of moving n-1 discs from source to spare peg is identical to our original problem, only difference being that the roles of the pegs change (spare peg becomes target and target peg becomes the spare peg)! This shows that we can recursively solve Towers of Hanoi.
0 Comments
Leave a Reply. |