Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does C # use Recursive algorithm to solve the Tower of Hanoi problem

2025-03-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report