Back to Blog
Hanoi towers recursion5/29/2023 You should also be able to simply copy and paste the code from here into Visual Studio 2003 and compile it. However, it will open and run correctly in Visual Basic 2005 Express Edition Beta2, which is freely available from Microsoft. The project is a Visual Studio 2005 Beta 2 Project and will not open in earlier versions of Visual Studio. Show Me The Code!Ī quick note about the code files included with this article. I imagine that many who might be reading this are scratching their heads right about now asking, "How (Why) does that work?" Let me say that I fully understand, and hopefully, seeing the code to make this work will help somewhat. That's all there is to it (more or less)! All of this will be done inside a single method in our class, and steps 1 and 3 are recursive calls back to that same method. Move n-1 discs back from the temporary post to the destination post.Move the last disc to the destination post. ![]() Move n-1 discs from the source post to the temporary post.So, since we already know how to move a stack of discs, the process looks like this (where n is the total number of discs in the initial stack): I realize that this is counterintuitive at this point, but bear with me. The algorithm that I have implemented starts with an assumption we are assuming that we already have the ability to move a stack of discs. you can never place a larger disc on top of a smaller one.only one disc can be moved at a time, and.There are two rules governing how discs can be moved: The goal is to get the stack of discs from one post to a different post. ![]() Basically, you have three posts, one of which contains a stack of discs that get smaller as you go up, like this: In case you’re not familiar with the Towers of Hanoi problem, I’ll describe it briefly here. ![]() I was told back in school that there was a way to write a non-recursive algorithm to solve the Towers of Hanoi problem, but after a little thought (and exposure to the recursive approach), I gave up trying to figure out what it is. Really, it is perhaps the best example of a clean, simple problem to demonstrate the power of recursion. The Towers of Hanoi problem is a classic exercise meant to torture, discourage, and otherwise torment all new computer science students (or, at least that’s what they think). The purpose of this article is to demonstrate a very clean, recursive algorithm for solving the Towers of Hanoi problem, coded in VB.NET.
0 Comments
Read More
Leave a Reply. |