The---Hanoi of Java recursive thought

Source: Internet
Author: User

In the books I have read, the best of the analysis recursion is the "Mathematics of Programmers" written by the Japanese Chicho.

Summarize:

Hanoi

Hanoi's Problem

?? Now we do not need to know what recursion is, and no need, we first look at a very classic game-Hanoi, the game is a mathematician Eduardo Lucas invented in 1883, the rules of the game, there are three fine columns (A, B, C), a column with 6 discs, the size of the disc is not the same, They are placed from top to bottom in order from large to small, and now we need to move all the discs on the a column to the B-pillar, and move with the following conventions:

    • Only one disc at the top of the column can be moved at a time.
    • Cannot enlarge disc on small disc

At this point, the Convention moves a disk from one pillar to the other to move the "1" time, so how many times does it take to move all 6 discs from A to B at least? Models such as:

?? Although the figure is very clear, but we still can not immediately find a particularly clear solution, so, we try to reduce the size of the problem, the 6 disk to 3 disk, first find out the solution of the 3-layer Hanoi, the model becomes:

?? The solution to the 3-layer Hanoi is relatively simple, we're going to move all 3 discs from A to B, we just need to move the smallest disk from a to B, then move the small disk from a to C, then move the smallest disk from B to C, then move the largest disk from A to B, then move the smallest disk from C to a , moving the minor disk from C to B, and finally moving the smallest disk from a to B, so that we have completed 3 of this Hanoi solution. Here we set the 3 discs from small to large to a,b,c, then the movement process is as follows:

/**   元素   过程       a    A->B       b    A->C       a    B->C       c    A->B       a    C->A       b    C->B       a    A->B    移动7次完结.. **/
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

The entire process is as follows:

?? From this, we can easily understand the 3-layer Hanoi solution, but think about it will find that 7 times we seem to be doing something repetitive: moving the disk, but the direction is different. Review the movement of ①②③④⑤⑥⑦ and then divide them into the following 3 scenarios:

    • In ①②③, moved 3 times to move 2 discs from the A-column to the C-pillar
    • In ④, the largest disk is moved from the A-column to the B-column
    • In ⑤⑥⑦, moved 3 times to move 2 discs from the C-pillar to the B-pillar

?? We found that the process of moving the operation is almost the same, but the direction of the movement is different, a->c and c->b two kinds, its process such as:

?? It can be seen from the diagram that although the destination of the two moves is not the same, but the operation of two moves is very similar, and we found that if the 3 movement as "Moving 2 disk" operation is "2 layer Hanoi solution", that is, in the process of solving 3 layers of Hanoi, we used "2 layer Hanoi solution “。 So, does that mean that solving the "4-layer Hanoi" process can be used to solve the "3-layer Hanoi solution"? Well, that's true, that's the law of Hanoi, yes, we've found it! In this case, we solve the previous 6-layer Hanoi problem, only need to solve the 5-layer Hanoi problem, and then use 5-layer Hanoi solution to solve the 6-layer Hanoi problem can be! Let's take a look at the process of using the 5 layer Hanoi to solve the 6-layer Hanoi, as follows:

?? We can see (a) and (c) is the 5-layer Hanoi solution, in order to understand the 6-layer Hanoi tower needs to use the 5-layer Hanoi solution, so as long as 5 layer Hanoi is solved, 6 layer Hanoi will be solved. And the solution of the 5-layer Hanoi? Yes, using the law we found earlier, we use the 4-layer Hanoi solution to solve the 5-layer Hanoi, the following process:

    • ①. First move the 4 discs from the A-column to the C-pillar, which is the 4-layer Hanoi
    • ②. Then move the largest disc (the largest disc in 5) from column A to column B
    • ③. Finally, the 4 discs are moved from the C-pillar to the B-pillar, i.e. the 4-layer Hanoi is reused.

So the 5-layer Hanoi is solved, and 4-layer Hanoi can use the same solution even with 3-layer Hanoi solution, 3-layer Hanoi and then use 2-layer Hanoi solution ... and so on, so that you have solved the 6-layer Hanoi, In fact, we know that with the solution of the 6-layer Hanoi, we can easily solve the 7-layer Hanoi, 8-layer Hanoi ... n-layer Hanoi, it is also easy to find this method of solving n-layer problems by using the known method of N-1 layer, The solution structure of each layer is the same, which solves the latter problem by using the result of the previous solved problem. In this way of thinking, we can summarize the solution of N-layer Hanoi, instead of using the specific ABC three pillars, but set them to X, Y, Z. In this case, X, Y, Z will not be fixed to a certain root of ABC in different situations. Here x is the starting column, Y is the target column, z is the relay column, and then the process of solving N-layer Hanoi is given. The solution for transferring n disks from the X-column to the Y-column using the z-column is as follows:

Blog :http://blog.csdn.net/javazejian[原文地址]/**当 n=0时,无需任何移动当 n>0时,    ①将n-1个圆盘从x柱,经y柱中转,移动到z柱(即解出n-1层汉诺塔)    ②然后将1个圆盘从x柱移动到y柱(最大的圆盘)    ③最后将n-1个圆盘从z柱,经x中转移动到y柱(即解出n-1层汉诺塔) **/
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

?? In order to understand the N-layer Hanoi from the above procedure, we also need to solve the n-1 layer Hanoi, and set it to H (N) For more general representation of the number of moves of the N-layer Hanoi. Using the above steps, you have the following relationship:

?? Mathematically we take a name for the H (N) and H (n-1) relations, called the recursive formula, known as H (0) and H (n-1), the method of H (n) must be known, as long as it is calculated sequentially, such as the 6-layer Hanoi recursive process is as follows:

Blog :http://blog.csdn.net/javazejian[原文地址]/**    H(0)=0                     = 1-1    H(1)=H(0)+1+H(0) = 1       = 2-1    H(2)=H(1)+1+H(1) = 3       = 4-1    H(3)=H(2)+1+H(2) = 7       = 8-1    H(4)=H(3)+1+H(3) = 15      = 16-1    H(5)=H(4)+1+H(4) = 31      = 32-1    H(6)=H(5)+1+H(5) = 63      = 64-1    .......                    = .........    H(n)=H(n-1)+1+H(n-1)       = 2^n -1**/
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

?? In this way, we know that the minimum number of moves for the 6-level Hanoi is 63 times (the formula for 2^n-1 only sums up the simpler calculation method). To this we will re-comb the whole process of Hanoi, in the solution out of the 6-storey Hanoi Tower, we can not find a solution to the method, so first try to solve the more simple 3-layer Hanoi, and in this process, we slowly found the solution of the problem of the general law of the Chinese Connaught Tower, Even with the solution of the n-1 layer to solve the N-layer Hanoi thinking way, through this way of thinking finally successfully solved the problem of the 6-layer Hanoi. In fact, the essence of this way of thinking is to convert complex problems into simpler, similar problems (recall the Hanoi solution) and then find out how to solve the complex problems by using simple similar problems, and this way of thinking is recursive!! Yes! Recursion is not an algorithm but a thinking mode of thinking, but we use this recursive thinking method to solve the program, the program is called Recursive algorithm, and recursion itself is a thinking way of thinking of the problem! Do we have a feeling of Huanran dawu to recursion? Or do you have a little understanding of recursion?

recursive way of thinking

?? With the above analysis, we can understand and use recursion, assuming now encountered a very complex problem, we also understand the ' simple problem is easy to solve ' the truth, then you can use similar to the Han Nota of the way of thinking, that is , Is it possible to determine whether the present complex problem can be transformed into a simpler homogeneous problem? If you can, then the first conversion to simple similar problems to solve, and then the use of simple similar problem solving to solve complex similar problems, this is precisely the essence of recursive thinking mode, well, this is recursion! Are you beginning to understand recursion now? We are reviewing the solution to the problem of the Hanoi Tower in order to deepen our understanding of recursion, such as:

?? It is clear that the N-layer Hanoi solution process, through the complex problem to the same simple problem to solve, the above graph also has a name called recursive structure, according to the structure we can set up before the H (N) recursive formula, it is obvious to find recursive structure and the process of establishing a recursive formula is very important, This will help us grasp the essence of the problem is through the N-1 layer Hanoi solution to solve the problem of N-layer Hanoi, such discovery ability needs us to have a relatively sharp insight and thinking ability, which requires us to encounter complex problems, more use of recursive thinking (complex problem simplification) way to think, to dig laws. Ok~, we believe we have a clearer understanding of recursion. Next we look at how to use the program to implement recursive algorithms and solve Hanoi problems.

implementation of recursive algorithm program for Hanoi

?? Through the previous analysis, we understand that the so-called recursion is to simplify the complexity of the way of thinking, and this way of thinking from the point of view of the program language is called a recursive algorithm, it through the function of the program directly or indirectly call the process of the function itself, recalling the previous analysis Hanoi recursive formula: H (n) =h ( n-1) +1+h (n+1)

We implement the Hanoi by the recursive algorithm of the program as follows:

Package com.zejian.structures.recursion;/*** Created by Zejian on 2016/12/11.* Blog:http://blog.csdn.net/javazejian [original address, please respect the original]* Hanoi recursive algorithm implementation */PublicClasshanoirecursion {/** *@param n Hanoi number of layers *@param x x Column Start column (A) *@param y y column target column (B) *@param z-column relay column (c) * Where a B C is only as a secondary consideration * *PublicvoidHanoiint N,Char X,Char y,Char z) {H (0) =0if (n==0) {Don't do Anything}else {Recursive formula: H (n) =h (n-1) + 1 + H (n-1)Move the n-1 discs from X to Z,y for the Hanoi of the relay column (N-1,x,z,y);-----------------------> Extract n-1 layer Hanoi: H (n-1)Move the largest disc to the destination column System.out.println (x+"+y");------------> 1Move the n-1 discs from Z to y,x for the Hanoi of the relay column (N-1,Z,Y,X);------------------------> Extract n-1 layer Hanoi: H (n-1)}}/** *@param n Hanoi number of layers *@param x x Column Start column (A) *@param y y column target column (B) *@param z-column relay column (c) * Where a B C is only as a secondary consideration * *PublicIntHanoicount (int N,Char X,Char y,Char z) {int movecount=0;H (0) =0if (n==0) {I don't do anything.Return0; }else {Recursive formula: H (n) =h (n-1) + 1 + H (n-1)Move the n-1 disc from X to z,y for the relay column Movecount + = Hanoicount (n1,x,z,y);-------------> Extract n-1 layer Hanoi: H (n-1)Moving the largest disc to the destination column Movecount + =1;---------------------------------> 1//Move the n-1 disc from Z to y,x for the Movecount +=hanoicount (n-1,z,y,x) of the relay column;  ---------------> Extract n-1 layer Hanoi: H (n-1)} return movecount;} //test public static void main (string[] args) {hanoirecursion hanoi=new Hanoirecursion (); System.out.println ("movecount=" +hanoi.hanoicount (6,' A ',' B ',' C ')); Hanoi.hanoi (3, ' A ',' B ',' C ');}}                

Traces of the recursive algorithm can be found from code:

/***Blog: Http://blog.csdn.net/javazejian [Original address, please respect the original]*/public void Span class= "Hljs-title" >hanoi (int N, char x, char y, char z) {//h (0) =0 if (N==0) {//do nothing}else {//calls itself function Hanoi () Hanoi (N-1,x,z,y); //move the largest disc to the destination column System.out.println (X+ "+y"); //call itself function Hanoi () Hanoi (N-1,z,y,x);}}      

?? Therefore, we also understand that recursive thinking in the program is the embodiment of recursive algorithm, and the recursive algorithm itself in the implementation of the program is the function call itself function, so everyone should always understand the recursive algorithm bar. Here is a bit to remind you, do not fall into the process of recursive internal thinking recursive algorithm, remember to understand the nature of recursive thinking (complex problem simplification) on the understanding of recursive algorithm, do not go through every step of the attempt to resolve the program to understand recursion (resolver execution is to give the function a real value, And then you step by step to launch the results, this way of thinking is wrong! ), that only gives you the result of pseudo-understanding (not really understanding). Remember! Recursion is not an algorithm, it is a simple way of thinking of complex problems, and this way of thinking is embodied in the program of recursive algorithm! Recursive algorithm in the implementation of the function is constantly calling itself the process!

definition of recursion

?? Through the above analysis, we finally understand recursion, then we give a formal definition of recursion, I believe that with the above basis, understanding the formal definition of recursion is relatively easy, recursion is actually an important concept in mathematics, and the recursive algorithm is designed for the purposes of programming, That is, the two forms of the different angles, but the essence is the same.
The definition of recursion (from a mathematical point of view): Defines itself directly with a concept itself. such as the factorial function f (n) =n! can be defined as:

The---Hanoi of Java recursive thought

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.