How does C # use Recursive algorithm to solve the Tower of Hanoi problem
This article introduces the relevant knowledge of "how C # uses recursive algorithms to solve the Tower of Hanoi problem". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
What is recursion
Method calls its own behavior is recursion, recursion must have a termination condition, otherwise it will be infinitely recursive.
1. Let's take a look at an example of recursion.
The Fact method of this program calls itself from large to small until the parameter is 1, and then it begins to return the cumulative multiplication from small to earth, and then calculates the factorial of number.
Static int Fact (int num) {if (num 0 & & levels)
< MAX_VALUE) { Move(levels, 'A', 'B', 'C'); Console.WriteLine($"一共移动了{Program.steps}次。"); Console.ReadKey(); return; } Console.WriteLine("输入范围错误"); Console.ReadKey(); } static void Move(int pile, char src, char tmp, char dst) { if (pile == 1)//pile=1问题就好解决了 { Console.WriteLine($"{src} -->{dst} "); steps++; return;} Move (pile-1, src, dst, tmp); Move (1, src, tmp, dst); Move (pile-1, tmp, src, dst);}
The running results are as follows:
This is the end of the content of "how to use recursive algorithm to solve the Tower of Hanoi problem in C#". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!