The reason is quite esoteric and has to do with the.Unfortunately, that results in a compilation error.("Towers after moving " + n + " from tower " + i + " to tower " + j) SolveHanoiRecursive (n-1, k, j) // Step 3. SolveHanoiRecursive (n-1, i, k) // Step 1. Static void solveHanoiRecursive (int n, int i, int j) towers, towers and towers are the three stacks. Next, suppose we want to maintain the state of each tower: Hint: think of a mathematical property you could exploit. The other() method now has above 10-12 lines of code.Ĭan you rewrite it to have only one line, a very short line, of code? We don't actually maintain the state of each tower. The above program merely prints out the moves needed.("⇒ Move disk# " + n + " from tower " + i + " to tower " + j) For now, we'll merely print out the move. Static void solveHanoi (int n, int i, int j) First find the third tower, other than i and j: , n are to be moved from tower i to tower jġ. Step 2: move disk N-1 from tower 0 to tower 1.There are three key steps in the recursion:.We will solve the problem using (of course) recursion: Write down the moves on paper as in "Step 1: Move disk 0 You can either cut out pieces of paper or find an interactiveĪpplet on the web. Work out the moves for the ToH problem with three disks. You cannot place a disk on top of a smaller one.You can move only a disk at the top of a tower.Goal: to move the disks to tower 1 using only. Initially, the disks are placed in tower 0, in the.There are three stacks (towers), numbered 0, 1, 2.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |