Hanoi towers recursion count java7/5/2023 ![]() ![]() Try giving a different number of dicks as user input and check the output. Hanoi(disks - 1, auxiliary, source, target)ĭisks = int(input('Enter number of disks: '))Ĭase 1: when number of disk is 4 Enter number of disks: 4Ĭase 2: when number of disk is 2 Enter number of disks: 2Ĭase 3: when number of disk is 1 Enter number of disks: 1 Move (N-1) disks from peg B to peg C using the intermediate peg A.ĭef hanoi(disks, source, auxiliary, target):.Move disk N (largest) from peg A to peg C using intermediate peg B.Move the first(N-1) disks from peg A to peg B using intermediate peg C.When N>1, then you can divide the original problem into three subproblems and solve them sequentially as follows. The problem has a recursive nature which leads to a straight forward recursive solution.Īssume there are N disks, if N=1, then you simply shift the disk from peg A to peg C. In case of three disks you can find the solution manually but for a larger number of disks like four or more than four then the situation becomes quite complex. Here is how you can solve the Tower of Hanoi problem for three disk. No larger disks can be placed on a smaller disk.Only top disk on any peg may be shifted to any other peg.A disk can be shifting from any peg to any other.Only one disk can be shifted at a time.There are some rules to solve this problem. Our objective is to shift all the disks from peg A to peg C using intermediate peg B. ![]() Initially, all the disks are placed over one another on the peg A. Let us discuss the problem by considering three disks. ![]()
0 Comments
Leave a Reply. |