Let's take a look at the recursive solution. It takes less than a minute to complete using the Perl language.
Sub hanno_recursive {
My ($ from, $ to, $ reserve, $ n) = @_;
If (1 = $ n ){
Print "move $ n from $ from to $ to \ n ";
Return;
}
Hanno_recursive ($ from, $ reserve, $ to, $ n-1 );
Print "move $ n from $ from to $ to \ n ";
Hanno_recursive ($ reserve, $ to, $ from, $ n-1 );
}
Extremely concise and elegant. It fully embodies the elegance of recursion.
Next, consider the iterative solution. Consider breaking down the problem into a tree structure. Obviously, when a B c is regarded as a circle, the left and right Subtrees have some symmetry. That is, clockwise or counterclockwise rotation.
In this way, we can use the left tree to obtain the right tree. The problem becomes linear recursion, which is easy to convert to iteration.
Now that you know the principle, it takes a lot of effort to write this code. It took an hour to adjust it.
Sub hanno_iterate {
My ($ from, $ to, $ reserve, $ n) = @_;
My @ left = ();
My @ right = ();
# Move to leaf node
My $ COUNT = $ N;
While ($ count> 1 ){
My $ TMP = $;
$ To = $ reserve;
$ Reserve = $ TMP;
$ Count --;
}
For (my $ Index = 1; $ index <= $ N; $ index ++ ){
My $ new = "move $ index from $ from to $ to \ n ";
Push @ left, $ new;
While ($ new = shift @ right ){
Push @ left, $ new;
}
Last if ($ Index = $ N );
If ($ index % 2) ==( $ n % 2 )){
# Anti-CLOCK $ from-> $ to, $ reserve-> $ from, $ to-> $ reserve
Foreach my $ OPT (@ left ){
My $ left_value = "$ Opt ";
$ Left_value = ~ TR/ABC/CAB /;
Push @ right, $ left_value;
}
} Else {
# CLOCK $ from-> $ reserve, $ reserve-> $ to, $ to-> $ from
Foreach my $ OPT (@ left ){
My $ left_value = "$ Opt ";
$ Left_value = ~ TR/ABC/BCA /;
Push @ right, $ left_value;
}
}
My $ TMP = $;
$ To = $ reserve;
$ Reserve = $ TMP;
}
Foreach my $ OPT (@ left ){
Print $ OPT;
}
}
Iterative Solution to the hanruata Problem