Hanoi Tower recursive algorithm implementation process


Introduction of Hanoi : https://baike.baidu.com/item/%E6%B1%89%E8%AF%BA%E5%A1%94/3468295


With picture:

 

 

Programming requirements:

Write a function with reference to the diagram to realize the shortest steps to move all the n pads from A to C , that is, print out the movement process of each step. (Such as A--->C , it means the process of moving the A position to the C position.)

 

initial analysis:

By observation, it is found that to move n pieces of mats from A to C , you need to move n-1 pieces ( the upper mats ) to the B position first, then you can move the lowermost mat to C , and finally move the n-1 pieces of mats from B. Move to C.

 

Because each time the logic is similar, a conjecture is drawn: this problem can be solved recursively ... Let's start to analyze the elements of recursion -

 

1. End condition: Obviously, the end of the mat movement is completed.

2. Changed parameters: the number of mats is reduced by 1 each time .

3. Common logic: To move n pads to C , you must first remove the upper n-1 pads, then move the lower pads to C , and then the goal becomes: to move n-1 pads to C , you must first move The top n-2 pads are removed, then...

 

 


Small scale chopper:

 

publicstaticvoid printMove(int n){  

if(n==0) return;

printMove (n-1); //move n-1 

System.out .println ( "A--->C" ); //Print the moving process 

printMove (n-1); //move n-1 

}

 

Results of the:

input:printMove(2);

Output:

             

input:printMove(3);

Output:

             

 

Analyzing the results, it is found that the number of times of printing is in line with the law of 2^n-1 , and the direction of thinking is no problem. But obviously such print results are only A to C , which does not meet our requirements. It is observed that the position transformation of ABC must be changed flexibly and may be passed in as a parameter.

And the bottom pad needs to be moved to C , and the upper pad may need to be moved from A to B , or from B to A. Be more sure of the idea just now, and start revising.

 

The final modification is as follows: (note the change of parameter position when calling the function)

 

publicstaticvoid printMove(int n,char A,char B,char C){  

if (n==0) return ; //The end of the movement of the mat

printMove (n-1,A,C,B); //Move the upper n-1 mat from A to B

System.out.println (A+ " --- >" +C); //Print (equivalent to moving the bottom pad to C each time)

printMove (n-1,B,A,C); //move the upper n-1 mat from B to C

}

 

test:

input:printMove(2,'A','B','C');

Output:

             


input:printMove(3,'A','B','C');

Output:

             


After multiple tests, there was no abnormal situation, and it was over.

 

 

Guess you like

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