Tower of Hanoi recursive algorithm

Recursive definition:

A recursive algorithm is the transformation of a problem into a sub-problem of the same kind that is reduced in size. The function (or procedure) is then recursively called to represent the solution to the problem.

A procedure (or function) calls itself directly or indirectly, such a procedure (or function) is called a recursive procedure (or function).

Features of recursive algorithm to solve problems:

(1) Recursion is calling itself in a procedure or function.

(2) When using the recursive strategy, there must be a clear recursive end condition, which is called recursive exit.

(3) The recursive algorithm is usually very simple to solve the problem, but the operation efficiency of the recursive algorithm is low. Therefore, it is generally not recommended to design programs with recursive algorithms.

(4) In the process of recursive calling, the system opens up a stack to store the return point, local quantity, etc. of each layer. Excessive recursion can easily lead to stack overflow and so on. Therefore, it is generally not recommended to design programs with recursive algorithms.

Example: Tower of Hanoi

Solution: (1) n == 1

             1st time plate 1 A---->C        sum = 1 time

       (2)  n == 2

             1st Disk 1 A---->B

             2nd disc No. 2 A---->C

             The 3rd set No. 1 B---->C sum = 3 times

  (3)n == 3

        1st Disk 1 A---->C

        2nd disc No. 2 A---->B

        The 3rd disc No. 1 C---->B

        4th set No. 3 A---->C

        The 5th disc No. 1 B---->A

        The 6th disc No. 2 B---->C

        7th set No. 1 A---->C sum = 7 times

 

It is not difficult to find the law: the number of times 2 of a disc is reduced by 1 to the power of 1

       The degree of 2 discs is 2 to the power of 2 minus 1

                         The number of 3 discs is 2 to the 3rd power minus 1

                         。  。   。    。   。 

                         Degree 2 of n disks minus 1 to the nth power

 Therefore: the number of moves is: 2^n - 1

Code:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325076645&siteId=291194637