SoFunction
Updated on 2025-03-04

Code analysis of the "Tower of Hannover" algorithm for recursive function solution

"Tower of Hannover" is a famous puzzle game. There are 3 columns and a set of hollow discs with different diameters on the tower. At the beginning, all the discs on the column are stacked in order from small to large. The goal is to move a bunch of discs to the target columns by moving one disc to another at a time, and the process is not allowed to place the larger discs on top of smaller discs.

If you interpret this passage carefully, if there are 10 discs or even more, then the operation steps are absolutely shocking, but the goal is to move a bunch of discs onto the target column. If you regard the 9 discs above as one set, the 10th disc as another set, first move 9 discs to another column, then look at the 8 discs above as one set, and the 9th disc as another set... and so on, decompose and move, and the idea of ​​recursive functions is reflected.

Complete the code, it is a very simple way to write it. I wonder if there is a simpler way to write it?

var hanoi = function {disc, begin, end, helper) {
 if (disc > 0) {
  hanoi(disc - 1, begin, helper, end);
  ('Moving Disc' + disc + ' from ' + begin + ' arrive ' + helper);
  hanoi(disc - 1, end, begin, helper);
 }
};
hanoi(3, 'Path One', 'Pillar Two', 'Pillar Three');

Output when the number of disks is 3:

Move 1 from pillar one to pillar three
Move 2 from pillar one to pillar two
Move 1 from pillar three to pillar two
Move 3 from pillar one to pillar three
Move 1 from pillar two to pillar one
Move 2 from pillar two to pillar three
Move 1 from pillar one to pillar three

The parameters passed to the hanoi function include the currently moved disk number and the 3 pillars it will use. When it calls Senior, it processes the disk above the disk currently being processed. Eventually, it will be called with a non-existent disk number. In such a case, it does nothing. Since this function ignores illegal values, there is no need to worry about causing a dead loop.

Summarize

The above is the code analysis of the JavaScript recursive function solution "Hanno" algorithm introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!